You're almost there, you just need to use std::pow() to raise a value to an arbitrary power, and add another for-loop to handle the repetetive work of filling in all the remaining columns:
for(int i = 0; i < A.size(); i++)
{
     A[i][0] = 2.0 + 0.1 * i;
     A[i][1] = 1 / A[i][0];

     for(int j = 2; j < A[i].size(); j++)
     {
         A[i][j] = std::pow(A[i][0], j);
     }
     ...
}


HackerRank: Fraudulent activity notification

Bad Habits
I'd get out of the habit of including bits/stdc++.h as it's non-standard and makes your compile times much longer than they need to be. Especially with such a short program.
Likewise, using namespace std can lead to problems and should be avoided.
Naming
You should use clearer variable and function names. The function name activityNotifications() sounds like it could be presenting the user with notifications. Or it could be processing activity notifications. Instead it's counting them. It might be better named countActivityNotifications().
Within the function, you have a few good variable names. Namely, median and results. I have no idea what dq stands for, which means I also have no idea what dq_idx stands for (beyond that it's an index for dq). expenditure is singular, but it holds multiple expenditures, so I'd make the name plural. d is unhelpful as well. Just because the problem description named the variables n and d doesn't mean your code should use those names. They should be numberOfExpenditureDays and numberOfTrailingDays. (If you prefer num to number and removing Of, that's fine.)
Simplify
You don't need to sort the expenditures. You can get the median by generating a histogram and finding the middle value. A histogram is just an array where each element is the number of times that value was in the input. So a histogram of expenditures would hold the count of how many expenditures were for 1 dollar, and 2 dollars, and 3 dollars, etc. Since the expenditures are between 0 and 200 dollars each, you would have 200 buckets in your histogram. Furthermore, since you're dealing with trailing days, once you have the first one calculated, you can simply update 2 values on each subsequent pass. (Decrement the expenditure from the day that's falling off the array and increment the one that's being added in.)
Your split_string() function goes to a lot of trouble to clean the string before you tokenize it. But you don't need to. You can simply not add empty strings to the results. Something like this:
void split(const std::string& s, std::vector<std::string>& results)
{
    size_t lastPos = 0;
    size_t nextPos = 0;
    while ((nextPos = s.find(" ", lastPos)) != std::string::npos)
    {
        std::string word = s.substr(lastPos, nextPos - lastPos);
        if (!word.empty()) {
            results.push_back(word);
        }
        lastPos = nextPos + 1;
    }

    if (lastPos != std::string::npos)
    {
        std::string word = s.substr(lastPos, std::string::npos);
        if (!word.empty())
        {
            results.push_back(word);
        }
    }
}

I had to read your function several times to realize what it was trying to do with std::unique(), std::string::erase(), and std::string::pop_back().
Readability
The activityNotifications() function is really hard to read due to the odd, inconsistent spacing it uses. I recommend a space before and after every operator to make it more clear. So this line, for example:
dq_idx=(dq_idx+1) %d;

is more readable when written like this:
dq_idx = (dq_idx + 1) % d;


You should never, ever, be using Select or Active... in your code.

Unless you explicitly want your sub to click on a cell, or you explicitly want to work off of a user-selection, this is an incredibly slow, inefficient,  fragile way of doing things.

This:

Range("A1").Select
Selection.FormulaR1C1 = "Knife"

Or

Range("A1").Select
ActiveCell.FormulaR1C1 = "Knife"

Is much better expressed like so:

Range("A1").FormulaR1C1 = "Knife"

Furthermore, Range("A1") is implicitly calling [ActiveSheet].Range("A1"). You should explicitly qualify your references to avoid bugs down the road. Like so:

ws2.Range("A1").FormulaR1C1 = "Knife"
ws2.Range("A2").FormulaR1C1 = "Fork"
ws2.Range("A3").FormulaR1C1 = "Spoon"

And then you can use a With statement to make it even better:

With ws2
    .Range("A1").FormulaR1C1 = "Knife"
    .Range("A2").FormulaR1C1 = "Fork"
    .Range("A3").FormulaR1C1 = "Spoon"
End With


Leetcode 17 : Letter Combinations of a Phone Number

Make mappings static constexpr
This mapping should never be changed, so ideally it should be constexpr. You also need only one instance of it, so it should be marked static as well (also, constexpr requires this). So:
static constexpr std::array<const std::string_view, 10> mappings = {
    ...
};

This also means getLetterMappings() can be made static constexpr, and in fact you can make dfs() static constexpr as well, although the constexpr part doesn't do much there.
Redundant check for empty input
Why do you check both digits.empty() and digits.size() == 0? Those expressions are equivalent. I would just check for digits.empty().
Unnecessary parameters curr_idx and N
Since you are passing the input digits to dfs() as a std::string_view by value, you don't need the parameters curr_idx and N. Just pass a modified version of digits to recursive calls to dfs(), like so:
void dfs(std::vector<std::string> &combinations, std::string_view digits, std::string &s) {
    if (digits.empty()) {
        combinations.push_back(s);
        return;
    }

    auto letters = getLettersMapping(digits.front());

    for (const auto &ch : letters) {
        s.push_back(ch);
        dfs(combinations, digits.substr(1), s);
        s.pop_back();
    }
}


Implementation of exp function in C using Taylor Series expansion

Termination condition not correct

To get the precision you request, you should stop the loop when x1 <= e, not when x1 / x0 <= e.  If you do that, you can now get rid of x0 because it no longer serves a purpose.  I adjusted your program to use the new termination condition and it gave me the results I believe you are looking for.  I also renamed e to precision because it was confusing for a variable to be named e when it didn't actually hold the value of the constant \$e\$.

#include <stdio.h>
#include <math.h>

int main(void) {
    double x1,precision,x,sum=0.0;
    int n=0;
    scanf("%lf %lf",&x,&precision);

    // Sums: 1 + x + x^2/2! + x^3/3! + x^4/4! + x^5/5! + ...
    //
    // To get an approximation of e^x.
    //
    // Stops when the next term to add becomes smaller than precision.
    x1=1;
    do {
        sum += x1;
        x1  *= (x/++n);
    } while (x1 > precision);

    printf("sum=%lf,\nexp=%lf\n",sum,exp(x));
    return 0;
}


Matlab code demonstrating use of fft (Fast Fourier Transform)

Your time vector definition is defined a bit strange, I would go for the more standardized form of

startpoint:stepsize:endpoint

endpoint = T*(L-1) % is this correct?
0:T:endpoint

Besides this you could perhaps add some comments in the calculate spectrum section, but for the rest it looks quite clear.


User-defined color implementation in windows console

If there exist a better alternative (color enumerator) to my code which is?

You should use the constants defined in a Windows header file named Wincon.h, which are as follows:

#define FOREGROUND_BLUE      0x0001 // text color contains blue.
#define FOREGROUND_GREEN     0x0002 // text color contains green.
#define FOREGROUND_RED       0x0004 // text color contains red.
#define FOREGROUND_INTENSITY 0x0008 // text color is intensified.
#define BACKGROUND_BLUE      0x0010 // background color contains blue.
#define BACKGROUND_GREEN     0x0020 // background color contains green.
#define BACKGROUND_RED       0x0040 // background color contains red.
#define BACKGROUND_INTENSITY 0x0080 // background color is intensified.

For example, you could write:

enum COLOR
{
    // Text foreground colors
    // Standard text colors
    GRAY_TEXT=FOREGROUND_INTENSITY,
    BLUE_TEXT=FOREGROUND_BLUE,

The answers to C++ Win32 Console Color should be useful to you.

Alternatively here's a copy-and-paste of the equivalent .NET enum for C#, which I believe uses the same bit-values and assigns conventional color-names:

#region Assembly mscorlib.dll, v4.0.30319
// C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\Profile\Client\mscorlib.dll
#endregion

namespace System
{
    // Summary:
    //     Specifies constants that define foreground and background colors for the
    //     console.
    [Serializable]
    public enum ConsoleColor
    {
        // Summary:
        //     The color black.
        Black = 0,
        //
        // Summary:
        //     The color dark blue.
        DarkBlue = 1,
        //
        // Summary:
        //     The color dark green.
        DarkGreen = 2,
        //
        // Summary:
        //     The color dark cyan (dark blue-green).
        DarkCyan = 3,
        //
        // Summary:
        //     The color dark red.
        DarkRed = 4,
        //
        // Summary:
        //     The color dark magenta (dark purplish-red).
        DarkMagenta = 5,
        //
        // Summary:
        //     The color dark yellow (ochre).
        DarkYellow = 6,
        //
        // Summary:
        //     The color gray.
        Gray = 7,
        //
        // Summary:
        //     The color dark gray.
        DarkGray = 8,
        //
        // Summary:
        //     The color blue.
        Blue = 9,
        //
        // Summary:
        //     The color green.
        Green = 10,
        //
        // Summary:
        //     The color cyan (blue-green).
        Cyan = 11,
        //
        // Summary:
        //     The color red.
        Red = 12,
        //
        // Summary:
        //     The color magenta (purplish-red).
        Magenta = 13,
        //
        // Summary:
        //     The color yellow.
        Yellow = 14,
        //
        // Summary:
        //     The color white.
        White = 15,
    }
}

If you're going to define your own enum then use it in your function declaration, i.e.:

BOOL setTextColor(HANDLE h, COLOR c)

... not ...

BOOL setTextColor(HANDLE h, WORD c)

I'd usually use mixed-case e.g. Color instead of COLOR for an enum; and I'd worry that it's already been defined in a header file.

Also I'd split it into two parameters instead of doubling the number of enum values, for example:

BOOL setTextColor(HANDLE h, ConsoleColor foregound, ConsoleColor background)
{
    WORD color = foregound | (background << 4);
    return SetConsoleTextAttribute(h, color);
}


Few additions

1) First get some unit tests in

2) I would do something like this http://jsfiddle.net/Brw4W/1/


Foreword

When developing your own version of some standard library or tool, I suggest you to specify how close to the standard version is along with the purpose behind it.
So, for istance:

Is it standard compliant?
Does it address anything missing?

Interface

What I find missing:

How can I reset the pointer?
How can I know how many "visitors" there are(that is, how do I get counter)? Note: It could be useful, but don't go too far and break the encapsulation!
An efficient way to visit the object, that is an alternative to std::weak_ptr:
How do I allocate/deallocate particular objects?

Implementation

#pragma once is not standard. Although almost all compilers implement it and seems like to be faster than header guards, I recommend these last ones at least until it gets standardized.
Why counter is allocated dynamically?
I understand you may not name swapp swap; however, there are better names, such as:

m_swap
internal_swap

C++, unlike C, makes no difference between function() and function(void).
Yes, they're both correct; but the first one is much more common.
new can throw std::bad_alloc. Especially in the second constructor, if new threw when allocating/constructing counter, ptr would be leaked.


Delete all virus-affected files with certain filenames

For what you are trying to achieve, Java has a very nice solution since Java 7: java.nio.Files.

The Files class comes with a lot of useful methods that do what you did more expressively and easier to understand.

Instead of listing all files in a directory and looping over them, you can actually walk the entire file tree, including sub-directories, if you want.

You can do this the "callback-style" or using Java Streams. I like streams, so I will try and rebuild what you did, but with java.nio.Files and java.util.stream.Stream. Also I am going to use Java 11's var keyword, because I don't like typing out all the types unless absolutely necessary:

/**
 * Deletes all files with their names ending in ".ccc" or starting with
 * "_how_recover_anj" or "_how_recover_jav".
 *
 * @param directoryName The directory to search in.
 * @return A map of all files which were attempted to be deleted and their
 *         deletion status.
 */
private static Map<File, Boolean> SearchAndDeleteFiles(String directoryName) throws IOException {
    try (var fileStream = Files.walk(Paths.get(directoryName))) {
        return fileStream.map(path -> path.toFile())
                .filter(file ->
                        file.isFile()
                        && (file.getName().endsWith(".ccc")
                        || file.getName().startsWith("_how_recover_anj")
                        || file.getName().startsWith("_how_recover_jav")))
                .peek(file -> System.out.println(file))
                // Actually delete the file and record the status.
                .map(file -> Map.entry(file, file.delete()))
                .peek(entry -> System.out.printf("%s delete status: %s%n", entry.getKey(), entry.getValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    } catch (IOException e) {
        throw new IOException(e);
    }
}

First you see, that I actually provide some documentation. Tell the user (even your future self), what this method is supposed to do, what is wants as parameters and returns as a result.

Also notice, that I removed the files argument. You changed that list and added the files that you traversed (not the ones that were successfully deleted) to that list. This is a code smell as you are modifying the incoming collection which could very possibly be immutable without checking.
In my solution, this is no longer necessary, as we don't need any recursion and actually return which files we traversed and attempted to delete.

Then I am following the recommendation written in the documentation and walk the file tree in a try-with-resources block. This makes sure, that in any case, the file handles to the directories are cleanly closed.

The stream is expressive and pretty self-explanatory, it first maps all the file paths to actual Java File objects, filters the ones matching your criteria, then prints the file name. You don't need to construct StringBuilders for every string you print, just more complex expressions and actually constructed strings.

Then it maps the file to itself and it's deletion status. This status is then printed, just like in your method and collected into a map.
The map is then returned.

If any exception is thrown, it is re-thrown and the stream of paths is cleanly closed.

The Files.walk method is implicitly recursive and lazy, so you don't need to worry about performance or traversing into sub-directories.

You could make this method even more flexible, if you want, but I hope this answers your question.


The code in the post, and the code in the answers by Joe Wallis and 200_success, traverses the whole of the input to collect the parities of all the items. But it is easy to return the result as soon as the outlier has been identified, avoiding a wasted traversal of the remainder of the input.

def outlier(it):
    """Given an iterable with at least 3 items, all of which have the
    same parity except for a single outlier, return the outlier.

    """
    count, item = [0, 0], [None, None]
    for n in it:
        parity = n % 2
        if count[parity] == 0 and count[1 - parity] >= 2:
            return n
        elif count[1 - parity] == 1 and count[parity] >= 1:
            return item[1 - parity]
        count[parity] += 1
        item[parity] = n
    else:
        raise ValueError("bad iterable")


Personally, I must say that close to all PDO derived/based classes I've seen so far suffer from the same problem: They are, essentially, completely pointless.
Let me be clear: PDO offers a clear, easy to maintain and neat interface on its own, wrapping it in a custom class to better suit the needs of a particular project is essentially taking a decent OO tool, and altering it so that you can't reuse it as easily in other projects. If you were to write a wrapper around MySQLi, I could understand the reasoning, but PDO? No, I'm really struggeling to understand the logic behind that unless:
You were to write a table mapper class to go with it, that establishes a connection between the tables you query, and the data models into which you store the data. Not unlike how Zend\Db works.
MySQL is, as you well know, not as flexible as PHP is in terms of data-types. If you are going to write a DB abstraction layer, common sense dictates that layer reflects that: it should use casts, constants, filters as well as prepared statements to reflect that.
Most mature code out there also offerst an API that doesn't require you to write your own queries:
$query = $db->select('table')
            ->fields(array('user', 'role', 'last_active')
            ->where('hash = ?', $pwdHash);

These abstraction layers often (if not always) offer another benefit, they build the queries for you, based on what DB you're connection to. If you're using mysql, they'll build a MySQL query, if you happen to switch to PostgreSQL, they'll churn out pg queries, without the need to rewrite thousands of queries. If you want to persist and write your own abstraction layer, make sure you offer something similar, too. If you don't, you're back to square one: embarking on a labour intensive, pointless adventure that won't be worth it.
An alternative approach is to extend the PDO class. Again, this has been done before and is, in theory, perfectly OK. Although, again this might be personal, it does violate one principle which is upheld by many devs I know: Don't extend, or attempt to change an object you don't own. PDO is a core object,so it's pretty clear you don't own it.
Suppose you were to write something like:
class MyDO extends PDO
{
    public function createProcedure(array $arguments, $body)
    {
        //create SP on MySQL server, and return
    }
}

And lets assume that, after some serious debugging, and testing, you actually got this working. Great! But then what if, some time in the future, PDO got its own createProcedure method? it'll probably outperform yours, and might be more powerful. That, in itself isn't a problem, but suppose it's signature were different, too:
public function createProcedure (stdClass $arguments)
{
}

That would mean you either have to ditch your method, and refactor your entire code-base to sing to the tune of PDO's latest and greatest hit, or you'd have to alter your method to:
public function createProcedure(array $arguments, $body)
{
    $arguments = (object) $arguments;//create stdClass
    //parse $body and:
    $arguments->declare = $body[0];
    $arguments->loops = (object) array('loop1' => $body[1], 'loop2' => $body[2]);
    $arguments->body = (object) array(
        'main' => $body[3],
        'loop1_body' => $body[4],
        'loop2_body' => $body[5]
    );
    return parent::createProcedure($arguments);
}

That would mean that, for all code you wrote, you're actually having to call 2 methods, turning your once so clever createProcedure method into dead weight. So what, you might say? Well, don't think you're out of the woods just yet, because This alternative method above is illegal, it can't be written, it can't work, it shouldn't work, it's just all shades of wrong, here's why:
The Liskov principle states that a child (the class extending PDO) may not alter the signature of inherited methods if those alterations constitute a breach of contract, meaning the expected types (type-hints) may not be stricter than or different to the types defined in the parent (ie: array vs stdClass is not allowed). Additional arguments are allowed, provided they're optional.
If the PDO method itself takes but a single argument of the type stdClass, then your child class may only add optional arguments, and should either drop the type-hint, or uphold it (ie: hint at stdClass, which would break all existing code), or don't hint at all (which is as error-prone as it gets).
What's more, after a couple of months, people might use third party code (frameworks), that rely on the createProcedure method, and pass it an instance of stdClass. You'll have to change your method again, to the vague, and error prone signature:
public function createProcedure($arrOrObject, $body = null)
{
    if ($arrOrObject instanceof stdClass)
    {
        return parent::createProcedure($arrOrObject);
    }
    if ($body === null)
    {
        //What now??
    }
    //parse body
}

If $body is null, and $arrOrObject is an array, the user might have structured the $arrOrObject array in the same way as PDO would like to see the object structured, in which case json_decode(json_encode($arrOrObject)); would do the trick (not casting, because a cast doesn't cast recursive), but it's just as likely that the code calling your method contains a bug. What to do? convert to an object, and try-catch, with the extra overhead that might cause?
This leads me to the last, and for now biggest omission:
When using a wrapper object, it's generally a good idea to implement a (slow) magic __call method, that checks if a method call was meant for the wrapper object, or if it was meant for the wrapped object.
Using your object, I might want to set another attribute on the PDO extension, but since you failed to implement the setAttribute method, I can't change the charset, nor can I change how PDO deals with NULL values. Which can only be considered to be a glaring omission. Especially since you expect the user to pass bare PDO constants to the constructor. Basically, the least you should do is add:
public function __call($method, array $arguments )
{
    return call_user_func_array($this->datab, $arguments);
}

This way, you semi-expose the actual wrapped object to the user, in the sense that, methods you haven't implemented can still be used. New methods that might be implemented in the future will automatically be accessible, too.
What's more, you'll be able to validate/check the arguments and log which methods are used by the users, so that you could fine-tune your class to better reflect the way it is being used.
Recap:

Building an abstraction class on a user-friendly raw-API like PDO is, IMHO, like a broken pencil: Pointless
Extending PDO means you don't have to create pass-through methods that call the wrapped API (like creating a prepare method), but it does mean there is a chance you'll have to refactor your code whenever PDO changes
If you still feel like using a wrapper object, either consider wrapping it around something less well known, but in some respects better (mysqli_* is what I'm hinting at), but implement the magic __call and, if required __callStatic methods.
Again, if you're going to procede: work on an entire abstraction layer, that allows for users to map tables to data models, and take it from there. Ensure that those data-models can be used easily to build HTML forms, for example in order for those forms to be linked to the DB in the blink of an eye, bot don't forget about sanitizing your data, of course.

On the code itself:
There is one thing you have to fix about your code, above all else, and that's your constructor:
I might choose to construct an object like so:
$database = new db("user", "pwd", "host", "mydb",
             array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ));

Setting the default fetch-mode to fetch objects, and the new instance of PDO will be passed the correct attribute array. Sadly, right after constructing that PDO object, you're deciding that the default fetch-mode should've been PDO::FETCH_ASSOC, because 2 lines further down:
$this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

I'd hate to use that code. Also, this just doesn't add up:
try
{
    $this->datab = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
    $this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
catch(PDOException $e)
{
    $this->isConnected = false;
    throw new Exception($e->getMessage());
}

Try-catch-throw? Why? The connection failed, the PDOException tells me why, that's what I want to know, why catch that exception, and throw a new, more general one? What if I passed PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT to the constructor, and the connection failed? You're probably better of replacing it with this:
$this->datab = new PDO($connString, array(
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'//careful with this one, though
));
foreach($options as $attr => $value)
{
    $this->datab->setAttribute($attr, $value);
}

And let the exception go. If the connection to the DB fails, the script can't do what it's supposed to do anyway. The PDOExceptions are usefull in a scenario where you're using transactions. If 999 queries succeeded, but the 1000th query failed, rather than inserting partial data, catching the exception, and rolling back the transaction is what you do, but catching an exception to rethrow it again is just silly.
But, again, I'm not going to stop you from doing what you want, perhaps you can prove me wrong and actually make something great. But in order to do that, you must know what's out there already:

As always start with the theory, wiki's a great place to start

the ORM wiki
The ActiveRecord Pattern wiki

doctrine

And all of its projects
Not in the least, its ORM

Propel, haven't used it, but N.B. recommended it
PHPActiveRecord
Zend\Db\Adapter and all of the components in the Zend\Db namespace
Even the old Zend_Db has something going for it, still


Formatting date difference in human-friendly terms

Chained ternary expressions in PHP are a major pain in the ass — don't use them!

You have a lot of tests that are redundant, since earlier tests will have already eliminated longer periods.  The error case at the end also seems pointless.

Use consistent indentation and braces for readability and safety — please don't skimp.

function dateDiff($date1, $date2)
{
    $date_1 = new DateTime($date1);
    $date_2 = new DateTime($date2);
    $diff = $date_1->diff($date_2);

    if ($diff->days > 365) {
        return $date_1->format('Y-m-d');
    } elseif ($diff->days > 7) {
        return $date_1->format('M d');
    } elseif ($diff->days > 2) {
        return $date_1->format('L - H:i');
    } elseif ($diff->days == 2) {
        return "Yesterday ".$date_1->format('H:i');
    } elseif ($diff->days > 0 OR $diff->h > 1) {
        return $date_1->format('H:i');
    } elseif ($diff->i >= 1) {
        return $diff->i." min ago";
    } else {
        return "Just now";
    }
}

Be sure to use consistent capitalization for "yesterday" and "just now".


File-exclusion based on an array of prefixes

you can use java.io.FilenameFilter like:

    final List<String> excludedFiles = Arrays.asList(filesToBeExcluded);
    File[] totalFiles = sourceDirectory.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return !excludedFiles.contains(name);
        }
    });


Wrapping a telephony RESTful service for sending text messages and making phone calls

In circumstances like you have here; the almost lowest level layer wrapping a dependency, it can be hard to see another layer lower to allow abstraction, but remember this: The lowest level wrapper of a dependency is a literal straight pass-through.

This means, if you take the twilio api and create a direct correlary that simply passes-through everything to the twilio api, then that wrapper is the lowest level wrapper and therefore bears no need of testing at the unit level (testing at the integration and build-verification levels however is worth while) as it has no actual functionality.

If you create such a wrapper, you may then pass in a mock of it to your next-level-up which is your provider here.

So i guess there are two rules I'm stating here, and glad to hear people give points for or against:

The lowest level wrapper possible of external dependencies is a direct pass-through (which feels stupid and tedious when writing it, but actually serves a purpose)
The lowest level wrapper of an external dependency has no need of testing at the unit level as it maintains no testable functionality, but should be tested at the integration and build-verification levels as well as all external dependencies should.

Also, for your particular case and similar ones, you have an obvious default implementation of the dependency that you will be wrapping so feel free to have a default constructor so its consumer's do not need to construct the twilio wrapper, while maintaining the ability for the twilio wrapper to be settable for the unit tests. Sometimes making the accessibility of these setters protected enough that consumers will not think it's ok to change it, while accessible enough for proper unit testing can be tricky; I tend to treat those situations with a use your best-judgement approach.

Edit:
I would unit test the Provider_Interface. Though that's one man's opinion, many people would say unit testing at this level is stupid, I maintain that where there is functionality, which your Provider_Interface has, there may be bugs. You could have a typo in 'SmsMessage' for instance, and therefore should unit test for these things. However I acknowledge there is much disagreement in industry about the ROI on unit testing at this level, or maintaining pass-through wrappers for such purpose as I am advocating.


Character Creation in Text Adventure; Proper use of Main and Global Values?

There is a way to pass the attribute name which you want to change, you can use setattr:

def change_stat(self, stat_to_change, new_number):
    setattr(self, stat_to_change, new_number)

However, there is no difference to what would happen if you just say self.strength = 10 instead of self.change_stat("strength", 10).

Regarding the need for global for the player character, there isn't. Just return the chosen class from the character_select function:

def character_select():
    barbarian = Character("Barbarian", 20, 10, 10)
    archer = Character("Archer", 10, 20, 10)
    wizard = Character("Wizard", 10, 10, 20)

    print("Welcome to TEST TEXT ADVENTURE RPG. Choose a character!")
    print("(A): " + barbarian.print_stats())
    print("(B): " + archer.print_stats())
    print("(C): " + wizard.print_stats())

    while True:
        user_answer = input().upper()
        if user_answer == "A":
            return barbarian
        elif user_answer == "B":
            return archer
        elif user_answer == "C":
            return wizard
        else:
            print("Invalid input! Try again.")

You could make it even nicer if you used a dictionary:

from collections import OrderedDict

def character_select():
    classes = OrderedDict([("A", Character("Barbarian", 20, 10, 10)),
                           ("B", Character("Archer", 10, 20, 10)),
                           ("C", Character("Wizard", 10, 10, 20))])

    print("Welcome to TEST TEXT ADVENTURE RPG. Choose a character!")
    for key, cls in classes.items():
        print("({}): {}".format(key, cls.print_stats()))

    while True:
        user_answer = input().upper()
        try:
            return classes[user_answer]
        except KeyError:
            print("Invalid input! Try again.")

You can then use it like this in your main function:

def main():
    player_class = character_select()
    print(player_class.print_stats())

You should probably rename your Character.print_stats function. Right now it sounds like it would actually print the stats, but it just returns them. So I would make your class like this:

class Character:
    def __init__(self, class_name, strength, dexterity, intelligence):
        self.class_name = class_name
        self.strength = strength
        self.dexterity = dexterity
        self.intelligence = intelligence
        self.health = strength*10

    def __str__(self):
        return "{self.class_name} " \
               "Health: {self.health} " \
               "Strength: {self.strength} " \
               "Dexterity: {self.dexterity} " \
               "Intelligence: {self.intelligence}".format(self=self)

If you are using Python 3.6, you can use f"{self.class_name} ..." instead of "{self.class_name} ...".format(self=self), which uses f-strings.

Because I named the function __str__, you can now do:

barbarian = Character("Barbarian", 20, 10, 10)
print(barbarian)
# Barbarian Health: 200 Strength: 20 Dexterity: 10 Intelligence: 10

And the loop in character_select becomes this, because str.format automatically calls str on its arguments, which will then invoke the Character.__str__ function:

for key, cls in classes.items():
    print("({}): {}".format(key, cls))

__str__ is one of the magic (or dunder) methods, which can give your class features so it acts like built-in classes. Have a look at this nice guide for a list and explanation of all of them.

Finally, you should add a if __name__ == "__main__": guard to allow importing your functions from other scripts:

if __name__ == "__main__":
    main()


First of all, you do not need to create an instance of Random class every time.

Then, you may use the ternary operator (the ?: operator) to select the array from which you want to take the element.

And, assuming that you have to take a random element form the array, you may use just a[T.Next(a.Length).

Random T = new Random();
. . .
string[] a = radioButton1.Checked? array.top:
             radioButton2.Checked? array.jung:
             radioButton3.Checked? array.mid:
             radioButton4.Checked? array.marksmen:
             radioButton5.Checked? array.supp:
             null;
if (a != null)
    textBox1.Text = a[T.Next(a.Length)];


Getting products by category, price, etc

OK, so I assume this is the code from your @Controller, there's a @Service that it calls, and the Service further calls a @Repository (the DAO layer). Furthermore, I shall assume you're using the latest version of Java, i.e. Java 8.
Ultimately I find it all depends on the number of products you have. Given not too many, you could do all the filtering in Java. Given thousands, you'd better do it in the database.
One method in the database layer
In any case, one database call is definitely much better than three, so you could just create a generic enough database search method to which you can pass all the search parameters. When you create the method, you could also create a data transfer object named, say, SearchParameters that contains all the search parameters. That way your method signatures don't grow to ridiculous lengths even when you search with several parameters. The interface will also be easy to change, because in order to add a new search parameter the method signature won't have to change, just the data transfer object.
Personal experience
The way I've solved a similar issue, with just a couple of dozen products, was that my DAO layer had a trivial public List<Product> findAll() method with a @Cacheable annotation so that after the first call to the DB the further ones would only access a fast cache in the memory.
The Service would then have the methods you described: getProductsByCategory, getProductsByManufacturer and getProductsByPrice, but they'd all just call the findAll() method of the DAO (quickly getting the cached response) and they'd filter the results based on their parameters.
For example (assuming the Product class has a getManufacturer() method that returns a String:
public Set<Product> getProductsByManufacturer(final String manufacturer) {
    return dao.findAll().stream()
        .filter(product -> Objects.equals(product.getManufacturer(), manufacturer)
        .collect(Collectors.toSet());
}

And that's it using Java 8's streams. The filter only includes those products whose manufacturer matches the given parameter.
One method in the service layer
However, since you need an intersection of three sets, you might as well create one method to do all of your filtering. Either to the DAO layer like I proposed in the beginning, or do it in your service layer if the amount of data is not too big, or databases aren't your strong suit. ;)
So, your business code would boil down to something like this:
New SearchParameters class:
import java.util.Optional;

public class SearchParameters {
    // Here with just one search parameter for brevity, but you'll get the idea
    String manufacturer;

    public boolean manufacturerMatches(final Product product) {
        return Optional.ofNullable(manufacturer).map(m -> m.equals(product.getManufacturer())).orElse(false);
    }
}

A method in your Service class:
public Set<Product> getProducts(final SearchParameters params) {
    return dao.findAll().stream()
        .filter(params::manufacturerMatches)
        .collect(Collectors.toSet());
}

Then just add more of those matcher methods to the SearchParameters class and deploy them as filter lines in your Service -- you can chain filters, so it's easy and really concise.
In case you're not familiar with Java 8's streams, .filter(params::manufacturerMatches) is a short-hand notation for .filter(product -> params.manufacturerMatches(product)), which in turn compares all the products against the manufacturerMatches method and only allows a product to go through if the method returns true.
Answers
So, to answer your questions...

Sets are basically good for holding those Products of yours in case you are not interested in the order of the products. If that matters, you need to use some List instead. But that's not really what you asked or wanted to know, so:
The issue with Sets in your code is that you duplicate or triplicate a lot of data and operate on many more objects than you need to in order to achieve your objective. Comparing big product objects is also more expensive (in terms of CPU cycles) than simple Strings or other such parameters, which would be enough for you. You could have all of the objects (Products) in one collection and just filter that. Also when you compare your objects in Sets, you need to be sure your equals and hashCode methods for the Products are always up to date -- if you forget to update them when you add a new field, you will get wrong results.

Yes, it's best to do just one DB call -- and even that one call can sometimes be omitted by using a cache. You can achieve that "one call only" by creating a bit more complicated DB query to account for all the search parameters or by handling the searching (filtering) in Java. Which way should you do it, depends on the factors I've listed above, i.e. mainly about the number of products in your database and your personal preference. But I wouldn't really use the Sets, as (like I said) they multiply the amount of objects you have, and also because I just don't find that .retainAll(...) kind of code very readable.


Reader-writers problem using semaphores in Java

The logic looks good in this program, but I am observing that there is a problem with readCount. Suppose if two threads (say t1 and t2) reach readCount++ at the same time. Initially, both will read the readCount value to be 0, and after being incremented by both, the value will be corrupted i.e., it may be 2 and the same will happen with readCount--.

The problem is that, according to the Java memory model, if this read and write for readCount are not atomic, we can declare the readCount as volatile:

volatile static int readCount = 0;

Will volatile resolve the problem:

Again, by declaring the readCount as volatile, it now makes the read and write operations atomic, meaning that every thread will read the updated value of readCount as there will be no optimizations by the compiler (as volatile declared). There will be only one copy of the variable and that will be in main memory, so every thread will read/write the value in main memory only. Now there will no variable copies in thread caches.

But still, this is not the full-proof solution, because increment/decrement operations on any variable are not atomic operations. readCount++ (or readCount--) is not a single operation and consists of these three operations:

Read readCount
Add one to readCount, i.e. readCount + 1, (readCount - 1, in case of readCount--)
Write the value (from step 2) again in readCount

Note: There are lots of links on Google about volatile, such as this one.

In order to solve this problem, I can think of two approaches:

synchronized block

We can write both increment (readCount++) and decrement (readCount--) operations in a synchronized block, because readCount is static. Will use a ReaderWritersProblem.class object for the synchronized block. Now, any thread that wants to enter the block first has to acquire the lock on the ReaderWritersProblem.class object. Then only it can proceed, otherwise it will wait. This way, we can make the increment/decrement operations atomic (which is actually composed of three operations, explained as above):

Replace readCount++:

synchronized(ReaderWritersProblem.class) {
    readCount++;
}

Replace readCount--:

synchronized(ReaderWritersProblem.class) {
    readCount--;
}

AtomicInteger class

We can use Java in-built atomic concurrent APIs i.e. classes in package java.util.concurrent.atomic. As readCount is of type Integer, we can go for an AtomicInteger class. This class provides methods for increment and decrement operations and guarantees the atomicity of these operations.

We can modify the code as such:

Replace the readCount declaration:

static AtomicInteger readCount = new AtomicInteger(0);

Replace readCount++:

readCount.getAndIncrement();

Replace readCount--:

readCount.getAndDecrement();

You can check here for more APIs in the AtomicInteger class.


JavaScript app to search GitHub using JSON API

Looks good to me. You could cache the ul:

var repoList = $("
").appendTo('#results');

So you don´t have to query the dom again when appending the list items.
Also it is better to build the list items in memory and only append the complete list to the dom. This way you only trigger one reflow.

So in the $.each loop I would

repoList.append($("
somerepo
"))

and then outside the loop

$("#results").html(repoList);


How can I find out why this Rust program to echo lines from stdin is slow?

I'm going to treat this as a code review question where the goal is to figure out how to write high-performance I/O code in Rust.

There are two critical steps to speed up Rust I/O:

Make sure the optimizer is turned on. Rust loops have terrible performance in debug mode. Turning the optimizer on should probably get you near 25 MB/sec or so, at least in my experience.
Avoid line-based I/O, or anything else which uses String values. For maximum performance, we want to work with raw byte buffers and avoid ever letting Rust call malloc or free.

Here's some code which drills down to fill_buf, which is about as low as we can go before losing generality:

use std::io;
use std::io::{IoError, IoErrorKind};

fn main() {
    let mut reader = io::stdin();
    let mut buffer = reader.lock();
    let mut writer = io::stdout();
    loop {
        let consumed = match buffer.fill_buf() {
            Ok(bytes) => { writer.write(bytes).unwrap(); bytes.len() },
            Err(IoError{kind: IoErrorKind::EndOfFile, ..}) => break,
            Err(ref err) => panic!("Failed with: {}", err)
        };
        buffer.consume(consumed);
    }
}

Of course, this means that you need to find the line breaks yourself, and be prepared for lines to be split over multiple buffers. Also, notice how I pass bytes.len() outside of the match block before trying to call buffer.consume(). This is necessary to placate the lifetime checker.

Trying this with pv:

cat /dev/zero | target/release/throughput | pv > /dev/null

…gives us a throughput of 527 MB/s.


Why is my C program for calculating Euler's constant of poor quality?

If you're to implement something like this, you should first learn about how these things are done. I hope this doesn't sound too harsh. To explain it better, here is my variant of your code, with comparison to what C computes as e using expl(1):

#include <stdio.h>
#include <math.h>

int main ()
{
    long double n = 0, f = 1;
    int i;
    for (i = 28; i >= 1; i--) {
        f *= i;  // f = 28*27*...*i = 28! / (i-1)!
        n += f;  // n = 28 + 28*27 + ... + 28! / (i-1)!
    }  // n = 28! * (1/0! + 1/1! + ... + 1/28!), f = 28!
    n /= f;
    printf("%.64llf\n", n);
    printf("%.64llf\n", expl(1));
    printf("%llg\n", n - expl(1));
    printf("%d\n", n == expl(1));
}

Output:

2.7182818284590452354281681079939403389289509505033493041992187500
2.7182818284590452354281681079939403389289509505033493041992187500
0
1

There are two important changes to your code:

This code doesn't compute 1, 1*2, 1*2*3,... which is O(n^2), but computes 1*2*3*... in one pass (which is O(n)).
It starts from smaller numbers. Let us, for a moment, assume that your factorials are correct (see below). When you compute

1/1 + 1/2 + 1/6 + ... + 1/20!

and try to add it 1/21!, you are adding

1/21! = 1/51090942171709440000 = 2E-20,

to 2.something, which has no effect on the result (double holds about 16 significant digits). This effect is called underflow.

However, had you started with these numbers, i.e., if you computed 1/32!+1/31!+... they would all have some impact.

Notice that 32! needs 118 bits, i.e., 15 bytes. Your long type doesn't hold as much (the standard says at least 32 bits; it's not likely it will hold more than 64). If we add printf("%ld\n", factorial(i)); to your main for-loop, we see the factorials:

1
2
6
24
120
720
5040
40320
362880
3628800
39916800
479001600
6227020800
87178291200
1307674368000
20922789888000
355687428096000
6402373705728000
121645100408832000
2432902008176640000
-4249290049419214848
-1250660718674968576
8128291617894825984
-7835185981329244160
7034535277573963776
-1569523520172457984
-5483646897237262336
-5968160532966932480
-7055958792655077376
-8764578968847253504
4999213071378415616
-6045878379276664832

See the negatives? That's when your (long) integer grew too much and restarted from its lowest possible value. Read about overflows; it's important to understand them.

By the way, I'm getting the same result (on my computer) even if I replace long with long long (and apply the proper printf format %lld).

Computing this kind of stuff is complex, and takes quite a bit of knowledge about how the numbers are stored in the computer, as well as the numerical mathematics and the mathematical analysis. I don't consider myself an expert, so so there might be more to this problem than what I've wrote. However, my solution seems in accordance to what C computes with its expl function, on my 64bit machine, compiled with gcc 4.7.2 20120921.


Find the first unique character in a string

One alternative is to let String.indexOf(int, int) do the iteration for you:

return IntStream.range(0, input.length())
                .filter(i -> input.indexOf(input.charAt(i), i + 1) == -1)
                .mapToObj(i -> Character.valueOf(input.charAt(i)))
                .findFirst().orElseThrow(NoUniqueCharactersException::new);

Loop with IntStream from 0 (inclusive) to the length of input (exclusive).
Filter for indices i where input.indexOf(input.charAt(i), i + 1) gives -1, i.e. there is no occurrence of the character at index i past that position.
For any matches, convert to our desired Character wrapper class using mapToObj().
In order to return the first character, we findFirst() from the IntStream, orElseThrow() our custom NoUniqueCharactersException.

A second alternative is to use String.lastIndexOf(int):

// instead of this
// .filter(i -> input.indexOf(input.charAt(i), i + 1) == -1)
// use this
.filter(i -> i == input.lastIndexOf(input.charAt(i)))

In this case, if the last index of the character at position i is indeed i, that means we have found our unique character.


Performance impact of using the universal selector in CSS

The problem with the universal selector is that... it's universal. It's affecting all descendants, present and future. Impact is not really noticeable in small scale, but when your app starts to grow (like packing more and more stuff in <td>), or if fast rendering is critical (like say render at 60fps for smooth animation), then the effects will show.

The way you're asking this question seems to imply that you're using tables for layout. Otherwise, <td> content shouldn't be that many to warrant a universal selector. Don't use tables for layouting. Tables don't get rendered until all the markup of the table (from <table> to </table>) is parsed. In the meantime, all you will be seeing is a big blank space. Not good.


Is the new version of this code more difficult to read and understand than the original? How can it be improved?

Disclaimer: I'm not too familiar with C#.

The modified form has expressions that are a little too complex for me, but either would be ok. My only comment is that the initial comment line is screaming for some notice:

// Only add corporate AD domain if the user is a member of it.

Why not take all the tests and put them into a function?

if ( IsMemberOfCorporateDomain( Thread.CurrentPrincipal ) ) ...

Then, depending on how you both feel about early exits:

private bool IsMemberOfCorporateDomain( IPrincipal currentPrincipal )
{
    if ( currentPrincipal == null ) return false;
    if ( !currentPrincipal.Identity.Name.Contains("\\") ) return false;

    var domainName = Utils.GetUserDomain(currentPrincipal);
    return string.Equals( domainName, Config.AppsSettings.Domain, StringComparison.OrdinalIgnoreCase )
}


Shell script to count chess game outcomes

I don't see the reason for chaining with -print0 | xargs -0.
It's better and simpler to use -exec:

find . -type f -name '*.pgn' -exec mawk -F '[-"]' '...' {} +

I don't see a way to make the AWK code faster,
but:

Some of the double-quoting is unnecessary
I would add a space around operators for somewhat better readability
A semicolon can be dropped

Like this:

/Result/ { ++a[$2] }
   END { print a[1] + a[0] + a["1/2"], a[1], a[0], a["1/2"] }


Transferring large amounts of data in web editor

I'd prefer a form with a textarea rather than a contenteditable element. Forms and text areas were built for that purpose.
As for your save code, GET requests should not do anything on the server. It should only do what it was called to do, and that is to get data. I suggest you do a POST or PUT instead by using a form, or via AJAX.
An advantage of AJAX compared to forms is that you won't leave your page. Similar to how you did it, you grab the data and send it to the server.
Your editor is risky since it can write to an arbitrary file on the server (or worse, on the system). With this code, I can modify this PHP file itself and make it do all kinds of stuff. I suggest you do some research on how you can restrict where and what you can modify.
You need a more robust approach in stripping HTML from the data than doing it manually. PHP has some built-in functions to do that for you, like strip_tags. There could be better solutions that I'm not aware of as well.
Massive data? How much data do you expect you put in anyway? I suggest polishing the implementation first before optimizing for other stuff, like data size and so on.


The comments on SO give some good hints. The most critical part is obviously blockIterator, so let's make it a separate function:

blockIterator
    :: ([Octet] -> [Octet] -> [Octet])  -- ^ pseudo random function (HMAC)
    -> [Octet]                          -- ^ password octets
    -> Int                              -- ^ iterations
    -> [Octet]                          -- ^ m
    -> [Octet]                          -- ^ a
    -> [Octet]

The implementation using folds on a list is nice and concise, but processing the list adds some unnecessary overhead, and prevents possible optimizations. If we instead rewrite it as a recursive function

blockIterator prf passwordOctets = loop
  where
    loop i m a | i == 0     = a
               | otherwise  = let m' = prf passwordOctets m
                                  a' = zipWith xor a m'
                               in a' `deepseq`
                                  m' `deepseq`
                                  loop (i - 1) m' a'

it gets somewhat faster. I also added deepseq on the octet lists so that they're fully evaluated at each round. Introducing the recursion inside loop, instead of making the whole blockIterator recursive allows GHC to inline it.

Measuring performance can be done using the criterion package:

import Criterion.Main

-- ...

main = do
    let stdtest n = pbkdf2HmacSha1 "password" "salt" n 20
    defaultMain [ bgroup "stdtest" $
                    map (\n -> bench (show n) (nf stdtest n))
                        [1, 2, 4096, 65536 ]
                ]

However, the far most time-consuming part is still processing lists inside blockIterator. Using unboxed ST arrays would make the code way faster. There would be no memory allocation in the loop, no need to force evaluation. The problem is, hmac_sha1 is implemented using list, so we'd need another optimized, ST-based implementation.


UserInfo information class with a database

Why do you do this:

if (this._userInfo.ContainsKey(Key))
    this._userInfo.Add(Key, "");

this._userInfo[Key] = NewValue;

Those first two lines are completely superfluous; moreover if you need to get a value from a Dictionary<T, T> and aren't sure the key is present, you need to use Dictionary<TKey, TValue>.TryGetValue.

Local variables like Reader need to be camelCase. Ditto parameters like Key and NewValue.

Why aren't you using an ORM like Entity Framework instead of this ugly, needlessly generic code? I mean: public string GetString(string Key), public int GetInt(string Key) -- really?


Handling SMS replies to register/unregister phone numbers

Here is my alternative. Your original code calls the DB for the same record twice (potentially) -- the get_or_create does the same as your try/except and creates the record.

def save_number(request):
    from_number = request.POST.get('From', '')
    subscribe = request.POST.get('Body', '').lower().strip()
    obj, created = SaveNumber.objects.get_or_create(phone_number=from_number)
    response = twiml.Response()

    if created:
        response.message("Reply with stellar and you're in! :-)")
    else:
        if subscribe == "stellar":
            obj.subscribed = True
            obj.save()
            response.message("You're in. Always text outtahere, and we'll remove you.")
        elif subscribe == "outtahere":
            obj.subscribed = False
            obj.save()
            response.message("You're out")
    return response

Disclaimer: i didnt actually test it theyre may be bugs


Function to send email, refactored based on SOLID principles

I'd still say that you should break apart the mail message and SMTP client into separate classes for the "Single responsibility principle". In specific:

  A class should only have a single responsibility, that is, only changes to one part of the software's specification should be able to affect the specification of the class.

This is usually where you have a MailFactory and a SmtpClientFactory that are injected into the class that actually does the sending (MailSender). The injection (by abstract, so interfaces) would be set into the MailSender to fulfill the "Dependency inversion principle"

  One should "depend upon abstractions, [not] concretions."

Side Note

This would also let you reduce MailFactory.CreateMailMessage to MailFactory.Create (and SmtpClientFactory.CreateSmtpClient to SmtpClientFactory.Create) but that isn't directly related to SOLID. You can get why in various API naming conventions, but the short answer is that it would be redundant.

Expansion

A reason for this is when you do unit testing. We have an abstract mail client that just sticks messages into an in-memory list in the order they are sent. That way, we can inject it into the sender as ISmtpClientFactory and the rest of the code still works, not knowing that we have taken out the entire implementation of the sending for testing.

Edit 2

You also want to avoid static in general. It is implied by "injecting" but I figured I'd clarify that. Create factory instances and pass them in. That way you can swap them out.


Am I optimally closing this modal window?

You can combine a couple of things: The close functionality can be function, and jQuery can operate on several elements at once:

function closeModal(event) { // passing in an event obj is optional
  $("#modal, #modal-overlay").hide();
  if(event) {
    event.preventDefault();
  }
}

$(".modal-close").click(closeModal);

$(document).keydown(function(event) {
  switch(event.keyCode) {
    case 27: // esc
      closeModal();
      break;
    case 9: // tab
      event.preventDefault();
      break;
    default: // everything else
      break;
  }
}

I've switched the keydown handler to use a switch statement, but that's not critically important. The point is just that since the keycode will be either one number or the other, there's no need for multiple ifs, and a switch is simple to extend if you need to handle more keycodes.


Assigning default values to function arguments which may be "empty"

use 5.008009 is insufficient here, since you're using the // operator, which was introduced in Perl 5.10.

This function feels awkwardly designed.  Generally, parameters that have default values appear after all required parameters.  Here, I would need to explicitly pass in undef as the first parameter to take advantage of the default.  Also note that the parameters for your is_CORE are backwards relative to Module::CoreList::is_core.

I also don't understand the benefit of having the empty string trigger the default.  I can understand having undef trigger the default.  I could also agree with having all "falsy" values trigger the default.  But this particular design feels weird.  If I had to do it, though, I'd write it like this:

sub is_CORE {
    use 5.008009; # perl v5.8.9; required for Module::CoreList to be available in CORE
    my ($module, $min_perl_version) = @_;
    $min_perl_version = '5.008009' unless defined $min_perl_version && length $min_perl_version;
    $Module::CoreList::VERSION >= 2.99 && Module::CoreList::is_core($module, undef, $min_perl_version);
}


This stuff is hard to get right, at this point good promise driven code seems more like an art than engineering.

From a CodeReview perspective, your code is fairly easy to follow, except for one thing which got me stumped for a little while, row_complete should really be named char_complete, and then suddenly addLettersRecursive will make more sense.

There are at least 3 additional ways you can deal with .then(function() { return function_that_returns_promise(args); });

Change your functions ( like addInput ) to return a function, like this:

function addInput(s) {
  return function addInputWrapper(){
    var l = $('.prompt:last');
    return addLettersRecursive(l, s);
  }
}

Then you can call simply .then( addInput( 'whoami' ) )
Create a generic wrapper function like this:

function wrap( f ){
  var args = Array.prototype.slice.call(arguments,1);
  return function wrapper(){
    return f.apply( this, args );
  }
}

Then you can call .then( wrap( addInput, 'whoami' ) )
Generate a lambdafy function like this :

function lambdafy( f )
{
  var lambda = function(){
    var args = Array.prototype.slice.call(arguments);
    return function(){
      f.apply( this , args );
    }
  }
  return lambda;
}

Then you can addInput = lambdafy( addInput ) and .then( addInput( 'whoami' ) )


I'm not a JS guy, so I focus on your HTML and CSS.

HTML

You're using the HTML5 doctype, so you can safely ommit the type-attribute on the script-tag
Add the viewport meta tag to the head-area to ensure correct viewport behavior on mobile devices:<meta name="viewport" content="width=device-width, initial-scale=1.0">(Note: I left out the self-closing / for the meta tag as well)
Avoid using ID's excessively; Things like caption and even a gallery itself are likely to occur multiple times on the same page – Classes are more appropriate there

CSS:

You have an error in the .imgThumbnails -rule, where you use a hover-property; There is no such property!
Side note: There is also no semi-colon. Although one can ommit the last semi-colon in a list of property-declarations, I highly encourage anyone not to do this. It just leads to unnecessary trouble
You're using a lot of fixed widths and heights. This is very restrictive and should be avoided.

Before I get deeper in to making suggestions on how to improve your code further, it would be great to have some kind of demo. This doesn't need to be a working example of your gallery, you can use placeholders instead of images.


Given a number represented as an array of digits, plus one to the number

Since you are returning a result.
Pass the parameter by const reference so that you don't accidentally modify it:

vector<int> plusOne(vector<int> const&  digits)

The less than operator is not defined for iterators.
You are just getting lucky.

for (it = digits.end() - 1; it >= digits.begin(); --it)

To iterate over a container in the reverse direction use rbegin() and rend()

for (it = digits.rbegin(); it != digits.rend(); ++it)

To help with efficiency you could reserve space in your result:

result.reserve(digits.size()+1); // The +1 is for cases where the result overflows.
                                 // Note: reserve() does not change the size of the
                                 //       vector just the underlying capacity.

Personally I would have refactored:

    if (sum > 9)
    {
        plus = 1;
        result.push_back(0);
    }
    else
    {
        result.push_back(sum);
        plus = 0;
    }

the body into:

    plus = (sum == 10) ? 1 : 0
    sum  = (sum == 10) ? 0 : sum;

    result.push_back(sum);


(Uh-oh: better - better define a quality measure!)

Your code doesn't tell what it's about.
constexpr looks good - "my" environment complains with C++11.
"The array&index manipulation" where "simultaneous assignment" is wanted is hard to read (could be worse: the elements of result[] could be non-interchangeable).
Alas, what I found for "modern C++" is ghastly compared to python's a, b = b, a + b. I appreciate the attempt to avoid avoidable assignments; I'm mildly curious if it makes any difference in the code generated by an optimising compiler.
Is there any better? Well, with output size limited by a constant, there's a tighter limit:
the runtime of your code is in O(1), just as any other.
In a comment, you express concern about the complexity of multiplication. If you accept ("bit-wise") "shift" as a (very) cheap operation, you can take three steps in the Fibonacci sequence at once without an increase in "logic gate complexity":

#include <cstdlib>
#include <tuple>
#include <iostream>

/// Iterates an a,b = b,a+b sequence in steps of three.
//constexpr
static unsigned long tri(int previous, int current, const unsigned int n) {
    if (n < 2)
        return n ? current : previous;
    std::div_t split = std::div(n-2, 3);
    while (0 <= --split.rem)
        std::tie(previous, current)
            = std::make_tuple(current, current+previous);
    unsigned long
        a = current - previous,
        b = current + previous;
    while (0 <= --split.quot)
        std::tie(a, b) = std::make_tuple(b, (b<<2)+a);

    return b;
}
/// Iterates the Fibonacci sequence in steps of three.
unsigned long fibonacci(const unsigned int n) {
    return tri(0, 1, n);
}
/// Iterates the Lucas numbers in steps of three.
unsigned long lucas(const unsigned int n) {
    return tri(2, 1, n);
}

(For variants using arrays of precomputed elements in stead of "the setup-loop" (and a main()), consult the edit history.)
(b*Phi³ coincidentally can be computed with just two summands (and no other power up to 2³² can).)


head and tail are partial functions, meaning that they are only defined for non-empty lists and will fail on empty ones. Because of this your capWord function is also partial and its strongly considered a bad practice to define such functions. In fact, the head and tail are also considered a bad heritage and in some alternative preludes it's been deliberately decided not to export such functions. So, firstly, you can redefine your function with pattern matching and make it total.

Secondly, you're introducing a redundant list for the first letter, instead you can prepend it using the : (pronounced "cons") operator.

Summing up we get the following definition:

capWord [] = []
capWord (h:t) = toUpper h : map toLower t

Alternatively (essentially the same):

capWord word = case word of
  [] -> []
  (h:t) -> toUpper h : map toLower t

The capitalize function is fine.


Method returning IEnumerable should ToList() or not

Does code that calls the method always expect List functionality (access by index, etc.)? Return a List. Does code that calls the method only expect to iterate over it? Return an IEnumerable.

You shouldn't care about what the caller does with it, because the return type clearly states what the returned value is capable of doing. Any caller that gets an IEnumerable result knows that if they want indexed access of the result, they will have to convert to a List, because IEnumerable simple isn't capable of it until it's been enumerated and put into an indexed structure. Don't assume that the callers are stupid, otherwise you end up taking functionality away from them. For example, by returning a List, you've taken away the ability to stream results which can have its own performance benefits. Your implementation may change, but the caller can always turn an IEnumerable into a List if they need to.

Now that you've decided what the return type should be, you have to decide what the implementation should use. Deferred execution has benefits, but can also be confusing. Take this example:

public static IEnumerable<int> GetRecordIds()
{
    return dbContext.Records.Select(r => r.Id);
}

IEnumerable<int> currentRecordIds = GetRecordIds();

dbContext.Add(new Record { Id = 7 });

// Includes "7", despite GetRecordIds() being called before the Add():
currentRecordIds.Dump();

This can be "remedied" by GetRecordIds calling ToList before returning. The "correct" use here simply depends on what is expected of the class ("live" results, or time of call results).

Again, don't assume the caller is stupid, and don't take away functionality from the caller by making assumptions about how it will be used. Remember, the interface tells you what is expected to be returned. IEnumerable only means you are getting something that can be iterated over (potentially streaming results and making use of deferred execution), and List only means you're getting an in-memory collection that can be added to, removed from, accessed by index, etc.

Edit - To address your "Update 1":

If you are really concerned, you might add some information into the documentation, but I don't think it's necessary. The IEnumerable interface doesn't claim to make any promises about performance on repeat enumeration (or even each iteration for that matter), so it's on the caller to handle it intelligently.


Project Euler # 53 Combinatoric selections in Python

just a little hack if you want a more fast solution,
can become faster if consider the similarity of the nCr and nC(n-r)

dic=[1]

for i in range(1,101):
    val =dic[-1]*i
    dic.append(val)

def choose(n,r):
    sol = dic[n]//(dic[n-r]*dic[r])
    return sol

def func(maxi, valu):
    count = 0
    for i in range(2,maxi+1):
        for j in range(1,i+1):
            val = choose(i,j)
            if  val>valu:
                count+=1
    return count

if __name__ == '__main__':
    from time import time
    START_TIME = time()
    print(func(100, 10**6))
    print(f'Time: {time() - START_TIME} seconds.')

just store all the value of factorial of a number upto 100 in dict and then process

update suggested by  @AJNeufeld , using list to store data than dictonary


Listening for several connections in an async method

I think Task.Factory.FromAsync is what you are looking for...

public async Task Start(CancellationToken token)
{
     while (!token.IsCancellationRequested)
     {
         Socket connectedClient = await AcceptAsync(this.socket).ConfigureAwait(false);
         ...
     }
}

public static Task<Socket> AcceptAsync(Socket socket)
{
     return Task.Factory.FromAsync<Socket>(socket.BeginAccept, socket.EndAccept, null);
}


Nice implementation, my suggestions:

Bug: text="aa aaa" and pattern="aaa" returns 1 instead of 3. Whether to handle this edge case  depends on your use case, but if text can be any string then it should be considered.
Input validation: if pattern is empty or null, a null pointer exception is thrown. You can fix it by adding a condition at the beginning of the method.
Naming: the method name search is too general. Consider a more specific one, like firstIndexOf or similar. The variable names set and addList also can be improved.
Arguments order: this is a personal opinion, but I would put the string being searched (text) before the string to search for (pattern).
Exception if not found: for such a function is common to return -1 instead of an exception when the pattern is not found. In doubt, document the method.
Testing: this method deserves more than one test, possibly using JUnit.
Complexity: the complexity seems to be \$O(textLenght*patternLength)\$. The outer for-loop iterates on text, while the inner for-loop won't do more than patternLength iterations otherwise pattern.charAt(index) will throw an exception. The time complexity of String#indexOf is \$O(n*m)\$ so  the main difference to your solution regarding complexity (worst case) is probably the space complexity. Anyway, it's better to focus on the correct functionality first and performance later.

As a reference this is the native implementation:
static int indexOf(char[] source, int sourceOffset, int sourceCount,
        char[] target, int targetOffset, int targetCount,
        int fromIndex) {
    if (fromIndex >= sourceCount) {
        return (targetCount == 0 ? sourceCount : -1);
    }
    if (fromIndex < 0) {
        fromIndex = 0;
    }
    if (targetCount == 0) {
        return fromIndex;
    }

    char first = target[targetOffset];
    int max = sourceOffset + (sourceCount - targetCount);

    for (int i = sourceOffset + fromIndex; i <= max; i++) {
        /* Look for first character. */
        if (source[i] != first) {
            while (++i <= max && source[i] != first);
        }

        /* Found first character, now look at the rest of v2 */
        if (i <= max) {
            int j = i + 1;
            int end = j + targetCount - 1;
            for (int k = targetOffset + 1; j < end && source[j]
                    == target[k]; j++, k++);

            if (j == end) {
                /* Found whole string. */
                return i - sourceOffset;
            }
        }
    }
    return -1;
}


Stylistic/Function

Your list holds values of type int yet you named the node type very specific in relation to file descriptors which will be a bit weird if you make a list of lets say prime numbers you want to operate on. Consider renaming your node type to something more generic rather than file (especially sincere there is a FILE type in <stdio.h>)
Your insert method actually doesn't insert an element, it appends it to the end so it should be named append.
delete doesn't work when the node you want to delete is head. I know you handle that case separately in get_choice but it's still bad that the caller has to know that fact. It also clutters the code with lots of special handling.
dump is a bit weird: It skips the first one, then prints all following nodes in order and then prints the first one. So while it prints out all nodes I'd say it's still unexpected from a usage point of view.
None of your methods can deal with the fact if NULL is being passed in.
If you typedef your structs then you can save some typing work.

Structural/Design

Your list does not have a nice API to use. You can see that in get_choice which is cluttered with handling of many special cases.
Some methods like insert (size/length would be a different candidate) are inefficient as you have to iterate the entire list first. You could avoid that by keeping a separate tail pointer.

I suggest you create a list object which holds head, tail and possibly length of the list and all your methods should operate on an object of that list type rather than nodes. Something along these lines:

typedef struct node_
{
    int value;
    struct node *next;
} node;

typedef struct list_
{
    struct node *head;
    struct node *tail;
    int length;
} list;

And then define some methods to operate on:

// creates a new empty list
list *new_list()
{
}

// deletes the list and all the nodes
void delete_list(list *l)
{
}

// appends new value to the list
void append(list *l, int value)
{
}

// insert a value at a given position
void insert(list *l, int value, int position)
{
}

// deletes the first node with the given value from the list
// return 1 if node found and deleted, 0 otherwise
int delete_item(list *l, int value)
{
}

// returns the first node with the given value or NULL if not found
node *find(list *l, int value)
{
}

// prints the content of the list
void print_list(list *l)
{
}

Your get_choice method would then look like this:

int get_choice(void) {
    int choice;
    int val;
    list *myList = new_list();
    while ( true ) {
        printf ("\n[Choices - Insert=1, Delete=2, Locate=3, Dump=4, Exit=5]\n");
        printf ("\nEnter selection: ");
        scanf("%d", &choice);
        switch (choice) {
            case (1):
                printf ("Enter value: ");
                scanf ("%d", &val);
                append(myList, val);
                break;
            case (2):
                if (myList->length > 0) {
                    printf ("Enter value: ");
                    scanf ("%d", &val);
                    if (!delete_item(myList, val))
                    {
                        printf ("Value %d not in list\n", val);
                    }
                }
                else {
                    printf ("List is empty!\n");
                }
                break;
            case (3):
                if (myList->length > 0) {
                    printf ("Enter value: ");
                    scanf ("%d", &val);
                    if (find(myList, val) == NULL) {
                        printf ("Value %d not in list\n", val);
                    }
                }
                else {
                    printf ("List is empty!\n");
                }
                break;
            case (4):
                if (myList->length > 0) {
                    print_list(myList);
                }
                else {
                    printf ("Nothing to dump!\n");
                }
                break;
            case (5):
            return 0;
        }
    }
}


Loading YouTube videos inside a bootstrap modal

Don't remove the indentation inside of code blocks so that the code is on the same line as the signature. It makes the code harder to read as it's hard to piece together which } goes to which signature.

For example, this:

function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
    videoId: 'zg8KE6bEP50',
    origin: 'http://rollnstroll.se',
    width: '640',
    height: '390'
});
}

Would become this:

function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
        videoId: 'zg8KE6bEP50',
        origin: 'http://rollnstroll.se',
        width: '640',
        height: '390'
    });
}

var tag = document.createElement('script');

The name "tag" is extremely general and gives little aid in defining the use of the variable. Since in the next line you give it a script source, I recommend calling it something that defines the script source.

Here is what I came up with

var ytIframeAPI = document.createElement("script");

Why are you inserting a script into the HTML via JavaScript? Why don't you just put the script tag in your HTML so it is loaded to start?

That way, you don't have to wait for the script to load from the source after the page has loaded; the script will load as the page is loading.

var fn = function(){
    player.playVideo();
};
setTimeout(fn, 200);

Again, like "tag", "fn" means nothing to the variable; I know that it is a function. The variable name does not have to tell me.

You have two options here:

Give it a better name.
Use an anonymous function.

Since the only purpose of that function is to use it in setTimeout, you can just use an anonymous function in place of fn.

Here is what I mean:

} else {
    setTimeout(function() {
        player.playVideo();
    }, 200);
}

See? I didn't even have to give the function a name.

This might just be a typo, but this confuses me:

if(typeof player.playVideo == 'function') {
    player.playVideo();
} else {
    var fn = function(){
        player.playVideo();
    };
    setTimeout(fn, 200);
}

If player.playVideo wasn't a function, it's going to go to else. Then, you call player.playVideo. Well, if it wasn't a function, how are you supposed to call it?


To reduce if/else you might want to introduce a separate function:

function showIf(selector, condition) {
    if (condition === true)
        $(selector).show();
    else
        $(selector).hide();
}

In this way you can simply write:

showIf('.arrow-controls .prev', position === 0);
showIf('.arrow-controls .next', position === totalSlides - 1);

Which, BTW, is what .toggle() does (see Jack's answer). I'd go a step further. You use those conditions extensively: I'd introduce some separate functions:

showIf('.arrow-controls .prev', isFirstSlideSelected());
showIf('.arrow-controls .next', isLastSlideSelected());

Note that if you want you might change showIf() to accept a function as condition and simply write:

showIf('.arrow-controls .prev', isFirstSlideSelected);

Few minor considerations.

You might want to use let instead of var, see also Is there any reason to use the “var” keyword in ES6?.

You may repeat var/let in each line, multiple declarations are sometimes misleading. Not to mention that when debugging and going through the code step by step that code you can inspect each declaration alone. See also Multiple var statements in JavaScript, not superfluous.

Do not align your declarations, visual appealing isn't important when you want to update one of those lines or you introduce a longer variable name...

If you reuse the same selector multiple times (you do) you should introduce a const for each of them, it will make changes in your HTML code much easier to handle.

Comments: your comments actually repeat what you already have in code, they do not explain anything more. Usually when I see/write this type of comments I feel I'm missing the opportunity to extract a separate function. Will you need to write "Show Hide Directional Navigation based on Slider Position" as comment if you call a function updateNavigationControlsVisibility()? Don't be afraid of reasonably long names, your minifier will do the job for you.


Identify MOT Dates which could be in various formats

Best practice is to get away from manipulating date strings yourself. And use Date types in your model.

So, when you parse the JSON, use DateFormatter to convert the non-user-friendly date strings to Date objects. And when presenting the dates in the UI, use another DateFormatter to present the date in a nice, user-friendly format. I’d also suggest using JSONDecoder for decoding the JSON into your model, so you don’t have to sprinkle your code with cryptic, error-prone, dictionary keys.

So, first, I would suggest specifying a date formatter when you decode. Because most of the dates are in the form yyyy.MM.dd, I’d use that. So, for example:

do {
    let decoder = JSONDecoder()
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.dateFormat = "yyyy.MM.dd"
    decoder.dateDecodingStrategy = .formatted(formatter)
    let result = try decoder.decode([Vehicle].self, from: data)
    print(result)
} catch {
    print(error)
}

The trick, though, is that one field, completedDate in MOTTest, uses a different string format, namely, yyyy.MM.dd HH:mm:ss, so I’d have JSONDecoder just parse that as a string, but then have a computed property to translate that one date/time string into a Date:

struct Vehicle: Decodable {
    let registration: String
    let make: String
    let model: String
    let firstUsedDate: String
    let fuelType: String
    let primaryColour: String
    let vehicleId: String
    let registrationDate: Date
    let manufactureDate: Date
    let engineSize: String
    let motTests: [MOTTest]
}

struct MOTTest: Decodable {
    private static let formatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.dateFormat = "yyyy.MM.dd HH:mm:ss"
        return formatter
    }()

    let completedDateString: String
    var completedDate: Date? { MOTTest.formatter.date(from: completedDateString) }
    let testResult: String
    let expiryDate: Date?
    let odometerValue: String
    let odometerUnit: String
    let odometerResultType: String
    let motTestNumber: String
    let rfrAndComments: [ReasonForRejection]

    private enum CodingKeys: String, CodingKey {
        case completedDateString = "completedDate"
        case testResult, expiryDate, odometerValue, odometerUnit, odometerResultType, motTestNumber, rfrAndComments
    }
}

struct ReasonForRejection: Decodable {
    let text: String
    let type: String
    let dangerous: Bool
}

That way, JSONDecoder not only does the decoding for us to our model structure (avoiding that unstructured collection returned by JSONSerialization), but it also converts all of those yyyy.MM.dd strings to Date instances for us. And for completedDate, our computed property takes care of that for us.

By the way, I used the following sample JSON:

[
    {
        "registration": "ZZ99ABC",
        "make": "FORD",
        "model": "FOCUS",
        "firstUsedDate": "2010.11.13",
        "fuelType": "Petrol",
        "primaryColour": "Yellow",
        "vehicleId": "4Tq319nVKLz+25IRaUo79w==",
        "registrationDate": "2010.11.13",
        "manufactureDate": "2010.11.13",
        "engineSize": "1800",
        "motTests":[
            {
                "completedDate": "2013.11.03 09:33:08",
                "testResult": "PASSED",
                "expiryDate": "2014.11.02",
                "odometerValue": "47125",
                "odometerUnit": "mi",
                "odometerResultType": "READ",
                "motTestNumber": "914655760009",
                "rfrAndComments": []
            },
            {
                "completedDate": "2013.11.01 11:28:34",
                "testResult": "FAILED",
                "odometerValue": "47118",
                "odometerUnit": "mi",
                "odometerResultType": "READ",
                "motTestNumber": "841470560098",
                "rfrAndComments":[
                    {
                        "text": "Front brake disc excessively pitted (3.5.1h)",
                        "type": "FAIL",
                        "dangerous": true
                    },
                    {
                        "text": "Nearside Rear wheel bearing has slight play (2.6.2)",
                        "type": "ADVISORY",
                        "dangerous": false
                    }
                ]
            },
            {
                "completedDate": "2018.05.20 11:28:34",
                "testResult": "FAILED",
                "odometerValue": "57318",
                "odometerUnit": "mi",
                "odometerResultType": "READ",
                "motTestNumber": "741489560458",
                "rfrAndComments":[
                    {
                        "text": "Nearside Parking brake efficiency below requirements (1.4.2 (a) (i))",
                        "type": "MAJOR",
                        "dangerous": false
                    },
                    {
                        "text": "Front brake disc excessively pitted (3.5.1h)",
                        "type": "DANGEROUS",
                        "dangerous": false
                    },
                    {
                        "text": "tyres wearing unevenly",
                        "type": "USER ENTERED",
                        "dangerous": true
                    }
                ]
            }
        ]
    },
    {
        "registration": "YY09DEF",
        "make": "BMW",
        "model": "Z4",
        "firstUsedDate": "2009.01.25",
        "fuelType": "Petrol",
        "primaryColour": "Green",
        "vehicleId": "3Fv916dPLGx=43PRaKa45e++",
        "registrationDate": "2009.01.25",
        "manufactureDate": "2009.01.25",
        "engineSize": "1800",
        "motTests":[
            {
                "completedDate": "2012.01.10 10:27:56",
                "testResult": "PASSED",
                "expiryDate": "2013.01.09",
                "odometerValue": "12345",
                "odometerUnit": "mi",
                "odometerResultType": "READ",
                "motTestNumber": "345655760009",
                "rfrAndComments": []
            }
        ]
    }
]

Needless to say, if you want to decode manually, like you did in your question, just have two parsing date formatters, one for the yyyy.MM.dd format and another for the yyyy.MM.dd HH:mm:ss format.

Finally, you might ask “how do I show these Date objects in my UI?”

You define UI date formatters:

let dateOnlyFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateStyle = .medium
    return formatter
}()

let dateTimeFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateStyle = .medium
    formatter.timeStyle = .medium
    return formatter
}()

Then you can do things like:

if let date = result.first?.motTests.first?.expiryDate {
    let string = dateOnlyFormatter.string(from: date)
    print("Expiry date:", string)
}

  Expiry date: 2 Nov 2014

And

if let date = result.first?.motTests.first?.completedDate {
    let string = dateTimeFormatter.string(from: date)
    print("Completed date:", string)
}

  Completed date: 3 Nov 2013 at 9:33:08

Clearly, use whatever dateStyle and timeStyle you want. But the idea is that we’ll show these strings in a nice, localized format as dictated by the user’s device settings.


CodeReview is a good place for this question....

There are a few things that you should consider...

Style

node is a bad name for a Java class. Standards for Java are that Class names are CamelCase, and your node class should be called Node.

Using == to compare double values is often a cause of bugs. In this case I believe it is 'safe', but you should be aware that it is, in general, a 'bad idea'.

It is typical, though not required, that when you have an if {.....; return ...} block that you do not have an else block. For example, you have:

if (this.hasNum(...)) {
    .....
    return returner.key;
} else {
    return Double.NaN;
}

In this case the else block is not necessary, and it could simply be:

if (this.hasNum(...)) {
    .....
    return returner.key;
}
return Double.NaN;

Otherwise, the style is good.

Logic

You actually loop through the tree three times. I presume hasNum(...) also walks the tree.

With problems like this you can reduce the problem to a single walk of the Tree.

node match = null;
node current = root;
node predecessor = null;
// walk the tree until we find our exact match....
// Our predecessor node will follow us whenever we take a right branch....
while (current != null) {
    if (current.key == num) {
        match = current;
        break;
    }
    if (num < current.key) {
        current = current.left;
    } else {
        predecessor = current;
        current = current.right;
    }
}
if (match == null) {
    return Double.NaN;
}
if (match.left != null) {
    predecessor = match.left;
    while (predecessor.right != null) {
        predecessor = predecessor.right;
    }
}
if (predecessor == null) {
    return Double.NaN;
}
return predecessor.key;


Performing non-production analytics on data

There are a few little things that can be improved:

-- For users 'sizeBytes' is the Table[ID] to allow sorting. Collissions are not a big deal
local function userAgregations(table, key, size)
   table[size] = key
end

If using LuaJIT, this function might be optimized away, but in regular Lua there's no reason to make a function that just does an assignment like this. Just do it straight in your code; table assignments are supposed to be understandable.

In genericAgregations (should be genericAggregations!) you're performing one table access too many:

local function genericAgregations(table, key, size)
   local value = table[key]
   table[key] = value and (value + size) or size
end

In printTopUsers, don't use a custom function in table.sort to sort in descending order. Sort normally and then perform the numeric for backwards.

Also, instead of concatenating str, create a temporary table, insert the bits of the string in it and in the end generate the string at once with table.concat. It's faster than multiple concatenations.

Same in printTable.

As for the redis-specific stuff, I have no knowledge but I hope the little tweaks above are useful!


Finding missing void keywords in C source code

I'm writing a bash script to search C source files and find the lines where I missed the void keyword

This alone suggests that your approach is very problematic. To do this properly you'd effectively need to write most of a C parser, and that isn't a good use of your time. There are other approaches that would get you more mileage and accuracy:

Double-check that your compiler (gcc?) for sure doesn't have warnings that cover your use-case; if it does, then simply compile and look at the output.
Failing that, reuse a parser. I recommend the Clang AST.

Bash is just the hideously wrong tool for this. Save yourself the pain of writing regexes that are both complex and likely missing many edge cases.


Hours and Minutes math in a work week calculator

It's a nice little program. Intuitively I'd prefer to input the times as 1:30 instead of 1.5, but that's just a personal preference.

The self.hours_worked field is redundant. It should simply be a local variable in the hours_left_update method. It's kind of weird that you reset it at the end of the method instead of initializing it at the beginning of the method. Anyway, just make it a local variable.

I played around a bit and came up with this code:

def hours_left_update(self):
    minutes_worked = 0
    for entry in self.entry_list:
        if entry.get() != "":
            try:
                minutes_worked += 60 * float(entry.get())
            except:
                pass

    minutes_worked = round(minutes_worked)   # just in case
    minutes_left = 40 * 60 - minutes_worked

    self.lbl8.config(text="{:02d}h {:02d}m".format(minutes_worked // 60, minutes_worked % 60))
    self.lbl10.config(text="{:02d}h {:02d}m".format(minutes_left // 60, minutes_left % 60))

Is there any reason for waiting 500 ms before updating the total times after each key press? I generally don't expect programs to have unnecessary delays.

I changed the output format for the two computed fields. As a result, the format changes after I press the first key because the labels are initialized with the old format. To make things consistent, I'd create the labels without any text and call self.hours_left_update() at the end of the constructor.

After cleaning up the rest of the code, it looks like this:

from time import strftime
import tkinter as tk
import datetime

class TimeClockApp(tk.Frame):
    def __init__(self, master, *args, **kwargs):
        tk.Frame.__init__(self, master, *args, **kwargs)

        self.now_lbl = tk.Label(master)
        self.now_lbl.grid(row=0, column=0, columnspan=2)

        tk.Label(master, text="Hours worked").grid(row=1, column=0, columnspan=2)

        self.entries = []
        weekdays = ["Monday: ", "Tuesday: ", "Wednesday: ", "Thursday: ", "Friday: "]
        for i in range(5):
            tk.Label(master, text=weekdays[i], anchor="e").grid(row=i+2, column=0, sticky="e")
            entry = tk.Entry(master, width=7)
            entry.grid(row=i+2, column=1, sticky="w")
            entry.bind("<Key>", lambda event: master.after(0, self.update_totals))
            self.entries.append(entry)

        tk.Label(master, text="Total Hours worked:").grid(row=7, column=0, sticky="e")
        self.time_worked_lbl = tk.Label(master)
        self.time_worked_lbl.grid(row=7, column=1, sticky="w")

        tk.Label(master, text="Hours left to 40:").grid(row=8, column=0, sticky="e")
        self.time_left_lbl = tk.Label(master)
        self.time_left_lbl.grid(row=8, column=1, sticky="w")

        self.update_clock()
        self.update_totals()

    def update_clock(self):
        now = "Current Date-Time: {} ~ {}".format(datetime.date.today(), strftime("%H:%M:%S"))
        self.now_lbl.config(text=now)
        self.now_lbl.after(200, self.update_clock)

    def update_totals(self):
        minutes_worked = 0
        for entry in self.entries:
            try:
                minutes_worked += 60 * float(entry.get())
            except:
                pass

        minutes_worked = round(minutes_worked)
        minutes_left = 40 * 60 - minutes_worked

        self.time_worked_lbl.config(text="{:02d}h {:02d}m".format(minutes_worked // 60, minutes_worked % 60))
        self.time_left_lbl.config(text="{:02d}h {:02d}m".format(minutes_left // 60, minutes_left % 60))

if __name__ == "__main__":
    root = tk.Tk()
    app = TimeClockApp(root)
    root.mainloop()

I did at least the following:

Start the method names with a verb.
Rename lbl8 to time_worked_lbl, and similar ones.
Only store those labels in self that are needed by the other methods.
Replace self.master with a simple master.
Made the formatting consisten, especially the spacing around named arguments.
Removed unnecessary lambdas.
Merge the two for loops into one.
Build the UI elements strictly from top to bottom.

Too bad that the grid method doesn't return self. That would have saved some more lines. :) By the way, this means that your code did something unexpected. It stored None into self.lbl1.


Welcome to Code Review. That is pretty useful tool. :) From the GitHub link, I notice that you're using Python 3. There are a few things, I think you'd benefit from:

Reorder your imports so that Python's library is imported first, followed by 3rd party modules; followed by your local display module. Read also the PEP-8 guide for the same.
Since you're combining requests and beautifulsoup4, I would suggest looking into Kenneth's yet another awesome project requests-html. You can have a single session to download the entire chapter/volume :)
Place your display initialisation code block inside the if __name__ == "__main__" clause.
You send a request more than once for the same page. First to get the page title, and later to actually start downloading images. Doing an HTTP request is heavy work. Do it once.
This looks ugly: open(title + "/" + volume + "/" + str(counter) + ".png", 'wb'). Use the with context block, and string formatting (python 3.6+):

with open(f"{title}/{volume}/{counter}.png", 'wb') as imagefile:
    imagefile.write(image.content)


There is not much to say about this code, it is fine.

You can get rid of incf and setf; the varying x is replaced by a variable named z; I express the comparison as a boolean variable greater (for lack of a better name), which gives:

(defun icbrt (x)
  "Returns the integer cube root of X."
  (check-type x (integer 1))
  (locally (declare (type (integer 1) x))
    (loop
       for s downfrom 30 to 0 by 3
       for z of-type integer = x then (if greater (- z b) z)
       for y of-type integer = 0 then (* 2 (if greater (1+ y) y))
       for b of-type integer = (ash (1+ (* 3 y (1+ y))) s)
       for greater = (>= z b)
       finally (return y))))

Note also that I removed the assertion and used check-type instead. While the additional comment is nice in the assert expression, it adds to the things developers have to maintain (think consistency of error messages), whereas check-type is supposedly already displaying the right amount of information to the user, and throws the right kind of exception.


I suggest that you do more error checking:

malloc or realloc may fail.
I can initialize the stack with negative capacity.
I can pop more elements than I pushed.

In all these cases, your implementation silently swallows the errors and accesses invalid addresses.

As πάντα ῥεῖ said in comments, if you want to store generic elements that exceed void* in size, you need to allocate memory for them and let the void* point to them, e.g.:

typedef struct {
    // ...
} BigStruct;

// pushing
BigStruct* data = malloc(sizeof(BigStruct));
// initialize *data
stack_push(&stack, data);

// popping
BigStruct* data = stack_pop(&stack);
// use *data
free(data);

Some small issues:

It is not common to cast the result of malloc or realloc in C.
If the stack is initialized to capacity 0, then the stack will never grow and elements will be stored at invalid positions.  A solution is to adjust the capacity to 1 automatically.