I see some things that may help you improve your code.

Avoid global variables

While you might only currently have a need for a single instance of your state machine, a better approach would eliminate the global variables.  Instead, it would make more sense to me to have each function return the new (end) state, or even better, have the state_transition contain the transitions implicitly.  Which you choose will depend on details of the real state machine.  For example, if it's a state machine for a communications protocol, the event might be "received a message header" and the next state may depend on whether the message header is valid or not.

Make your state table complete

The STATE_END and EVENT_END are not represented within the state table.  The problem with that is that anyone reading the code might easily overlook those two possibilities because they're not in the state table.  On the other hand, the EventId and StateId members are never used and should be omitted.

Use the appropriate types

The s and e variables are both declared int but they're really not.  They should instead be States and Event types.

Chose better names

The event enum is called Event (singular) but the state enum is called States (plural) which is confusing.  I'd recommend using the singular form for both names.

Simplify your typedefs

In this case, there is no need to repeat the name Event or the name State in the typedef.  You can make it an anonymous enum with a typedef:

typedef enum
{
    eEVENT_X,
    eEVENT_Y,
    eEVENT_Z,
    NEVENTS
} Event;

Note that this construction makes this line unnecessary:

#define NEVENTS 3

That makes it a little easier to maintain the tables.

Implement range checking

What happens if some energetic gamma ray flips a bit in your embedded device's RAM and the value for the state goes from 1 to 129?  The answer is that the code will use whatever arbitrary code is that far off the end of the state table.  It's prudent instead to have a range checking function wrapper so that bad values (which might more plausibly be a result of a program error somewhere) will not cause the system to crash.  Here's a range checking function that could be used:

bool applyEvent(State *s, Event *e)
{
    if (*s >= NSTATES || *e >= NEVENTS)
        return false;
    *s = stateTrans[*e][*s].function(e);
    return true;
}

Note that it also assumes that each function is of this form:

State function_eZsY(Event *e)
{
    printf("\n zy \n");
    *e = eEVENT_Z;
    return eSTATE_Z;
}

Using this, there are no longer any global variables and the main function can look like this:

int main()
{
    State s = eSTATE_X;
    Event e = eEVENT_X;
    while(applyEvent(&s, &e))
    {
    }
}

Which brings us to the last point:

Eliminate return 0 at the end of main

Since C99, the compiler automatically generates the code corresponding to return 0 at the end of main so there is no need to explicitly write it.


Find size for elements to fit in certain width

Using a template variable in the script means you have this script in the HTML document and repeat it for each owl carousel. That is a vary bad idea, mostly because that way you may have multiple functions with the same name.

Generally your HTML shouldn't "know about" (reference) your JavaScript. Instead the JavaScript should find the elements it wants to attach itself to.

Put the function in a separate script file (together with all of your other scripts, wrapped in an IIFE) and include it once with <script src="..."> at the end of the HTML.

Then place a class on all owl carousels you want to apply the function to and use that to call the script for all and any elements with this class. For example, with jQuery:

(function() {

    $('.owl-carousel--adjust-height').each(function () {
        _AdjustHeightOwlDots($(this));
    };

    function _AdjustHeightOwlDots(owlCarousel) {
        // ...
     }

})();

Now, inside "find" the sub elements (and save references to avoid duplicate queries of the same elements):

const dots = owlCarousel.find('.owl-dots');
const dotRowWidth = dots.width();
const amountOfDots = dots[0].childElementCount;
const dotButtons = dots.find('> button');
const singleDotWidth = dotButtons.width();

(You learn new things every day. Never heard of childElementCount before this - and it's not even a new thing.)

In setNewStyle the query is also repeated and can be replaced with chaining (or the alternative syntax for .css() using an object) and also can be moved outside the function:

const dotButtonSpans = dotButtons.find('> span');

const setNewStyle = function(hw, margin) {
    dotButtonSpans
        .css('width', `${hw}px`)
        .css('height', `${hw}px`)
        .css('margin', `5px ${margin}px`);
}

Or

const setNewStyle = function(hw, margin) {
    dotButtonSpans.css({
        width: `${hw}px`,
        height: `${hw}px`,
        margin: `5px ${margin}px`
    });
}

Finally the big if block can be replaced with a simple calculation (including removing the part that makes maxDotWidth even, instead using | 0 as a short cut to round numbers to integers):

const size = ((maxDotWidth / 4) | 0) + 1;
const margin = maxDotWidth < 2 ? 1 : (((maxDotWidth - 2) / 4) | 0) + 1;

setNewStyle(size , margin);


You should use braces {} for single if statements too. This makes your code less errorprone.

If you are refactoring some code you should be sure to have good tests at your hand to validate that the refactored code behaves like the old code.

By extracting the check for all these this.xx() properties to a separate method like

private static bool ShouldReturnCurrentDescriptor()
{
    return (this.IsObjectBeingValidated) ||
           (this.Locked) ||
           (!this.IsReadOnly && (this.IsNewInCorrection || this.ImportedDataMD5 != null));
}

The former code can be refactored to

TableTypeDescriptor baseDecriptor = base.CustomTypeDescriptor as TableTypeDescriptor;

if (ShouldReturnCurrentDescriptor() ||
    (baseDecriptor.OldTableDescriptor == null))
{
    return baseDecriptor;
}
return baseDecriptor.OldTableDescriptor;


My own twist on the classic "Guessing Game" script in Python

Using the right functions

What you want to do is present the string xyz in some order. For that, there's random.shuffle(). Doing sampling is for taking a small number of elements from a large set (think, drawing a poker hand from a deck), and is not well suited for this particular problem. So we can start with:

answer = 'xyz'
random.shuffle(answer)

Note that a string in python is also an iterable, you don't have to make it a list of strings. Also your str() in your loop does nothing - and the loop itself is just a very verbose copy. Just the shuffle suffices.

Your outer loop

Your logic looks like:

while cond:
    ...
    if cond2:
        break
    else:
        break

That is, the outer loop never matters. len(keys) > 0 for sure the first time through and then we never check it again, so we can simply drop it.

Iteration

There's no reason to write list(enumerate(iterable)) if you're just looping over it. That unnecessarily has to bring the entire enumeration into memory to construct the full list. You only need one element at a time - so let the iterable give you one element at a time.

We can also make this much more readable by naming things better:

for round, letter in enumerate(answer):
   ...

Why are we enumerating anyway?

Enumerating is for enumerating. But here, the round number doesn't actually correspond to the letter number. It should just be an external variable:

round = 0
for letter in answer:
    while attempts > 0:
        round += 1

        print 'Round {}'.format(round)
        guess = input('> ').lower()

        if guess == letter:
            print('Correct!')
            break
        elif len(guess) > 1 or guess not in answer:
            print('Invalid option')
        else:
            print('Wrong!')
            attempts -= 1


Make 10 from the numbers 1,1,5 and 8 using the 4 operations, by brute force

I like your code but don't have a solution that improves on brute force. Just a few comments:

(1) You can eliminate your for loop assigning to res3 like so:

res3 = data.frame(V1 = unlist(lapply(res2$expr, function(temp) sapply(1:6, function(j) insert_str(temp,c("(", ")"),x[j,])))))

Whether this is a good idea is debatable, but it's slightly faster when I test it as compared to the for loop (a difference of about 10%). Perhaps lapply would become more advantageous as you increased the number of digits or operations to be explored.

(2) The obvious speed-related comment is to use data.table. This is another change that will more noticeably improve performance as you move to a larger-scale problem since you can benefit from the in-place operations.

(3) You are working with a manageable set of numbers here, but in the future you might want to seek solutions in parts. For example, check half the possibilities and only check the other half if you don't find a solution. Similarly, you don't have to assume there's only one set of parentheses but could make the choice to check the second set if your first search yielded no results.

(4) When you know the numbers in advance or you're coding to a specific set of numbers, it might be helpful to eliminate all rows that have a certain combo that couldn't possibly be in a correct answer. For example, I'd get rid of anything with 8*5 or 5*8 since nothing you can do with the 1's can bring that expression down to anything close to 10. Similarly I'd get rid of anything with 1/1 and 1*1 since these also can't lead to a solution.  Doing this would eliminate 1152 out of 4608 possibilities. (Note that I'm relying on standard order of operations rules.)

I don't feel any of these comments are super helpful but wanted to write since I enjoyed reading your code and since Code Review doesn't always give much feedback to us R users. Hopefully others will add more interesting things.


This was working fine, but it just seems hard-coded and wrong.

It's a monolythic monster. It works, but if you have the time, you could benefit from re-writing it (using c++ alternatives).

  How can I make the size of FormBuffer to be dynamic instead of 1024?

Like so (C++):

bool SendBasicInfo(USER* user, SOCKET sock)
{
    std::ostringstream FormBuffer; // <<< here

    char DataType1[] = "a=";
    char DataType2[] = "&b=";
    char DataType3[] = "&c=";

    char FormAction[] = "/g/g.php";

    // get: length of the actual content
    auto ContentLength = strlen(user->user_id) +
        strlen(user->pcname) +
        strlen(user->username) +
        strlen(DataType1) +
        strlen(DataType2) +
        strlen(DataType3);

    // header
    FormBuffer << "POST " << FormAction << " HTTP/1.1\n";
    FormBuffer << "Content-Type: application/x-www-form-urlencoded\n";
    FormBuffer << "Host: \n";
    FormBuffer << "Content-Length: " << std::to_string(ContentLength) << "\n\n";

    // actual content
    FormBuffer << DataType1 << user->user_id;
    FormBuffer << DataType2 << user->pcname;
    FormBuffer << DataType3 << user->username;

    const auto str = FormBuffer.str();

    std::cout << str << std::endl;

    return ( send(sock, str.data(), str.size(), NULL) >= str.size() );
}

Otherwise (if you want to write C code), you will have to iterate over the entire data once and compute it's resulting size, then allocate memory for the result, then iterate again over the data to create the buffer contents, then sent to socket and remember the result in a variable, then free the allocated memory, then deturn the stored result. If it sounds ugly, that's because it is :D.

Edit: The HTTP standard states that you should send \r\n at the end of header lines, not \n. It may not matter much in effect though, because both servers and clients are mandated to receive and parse both variants - as developers tend not to respect this rule (I may be remembering it wrong though).


Returning information about the result of a file processing, without using output parameters

As one of the commenters pointed out, adding a boolean flag to your result is one of the better ways to go about returning a successful result, especially when compared to returning null. In fact, I have a wrapper around a search result object where I do exactly this in the code for my current project.

  "null" makes me think of "something wrong".

This is exactly why null should not be used for this situation. At worst you'll have a programmer later who is totally confused about what is going on in your code, as most people will not return null from a function, especially for successful completion of that code.

This is the code I use:

public class SearchMemberEligibilityWrapper
{
    public List<RegularMember> ResultList { get; set; }
    public int ResultCount { get; set; }
    public bool ResultSuccessful { get; set; }
    public SearchType ResultSource { get; set; }
    public string ResultError { get; set; }

    public SearchMemberEligibilityWrapper()
    {
        this.ResultList = new List<RegularMember>();
        this.ResultCount = 0;
        this.ResultSuccessful = false;
        this.ResultSource = SearchType.Default;
        this.ResultError = string.Empty;
    }

    public enum SearchType
    {
        Default,
        QNXT,
        Database,
        Historical
    }
}

Then the code that uses the SearchMemberEligibilityWrapper checks for the value of ResultSuccessful to decide what to do after the search attempt. You have three states that the search result can exist in:

Search unsuccessful (error)
Search successful, 0 results
Search successful, >0 results

If you're concerned about having multiple errors per file, then using this pattern you can even have a List<string> property for your errors, and list your errors individually, rather than simply having one error for everything.


Splitting the Java builder to avoid writing same code multiple times

The builder instance can be extracted into a dedicated reference and you'll be able to apply the common instructions on it only once, for example:

final Problem.Builder builder = new Problem().builder().locationID(condition.getLocationID());
final String indexName;
if (condition.getOwner() != null) {
  indexName = sourceLocation;
  builder.sourceLocation(condition.getSourceLocation());
} else {
  indexName = currentLocation;
  builder.currentLocation(criteria.getcurrentLocation());
}
final Problem hashProblem = builder.build();


Overview:
You need to concentrate on writing self-documenting code. This basically means using self-documenting variable names and writing functions that do specific obvious self-documented tasks.
int main(int argc, char* argv[])
{
     // Handle command line arguments.
     // Set appropriate variables.

     playGuessNumberGame();  // Pass parameters you extracted from
                             // command line or environment.
}

void playGame()
{
     int  hiddenNumber = getNumberFromPlayer();
     bool finished     = false;

     while(!finished) {
         int guess = getNumberFromPlayer();  // Or calculate guess ?
         printHint(hiddenNumber, guess);

         finished = guess == hiddenNumber;
     }
}

Another thing I would think about is storing state in an object that is updated. In this case you have the guess that is updated based on whether it was lower or higher. I would wrap this logic into an object that understands how to use this data:
class Guesser
{
     int   min;
     int   max;
     int   currentGuess;
     public:
         Guesser(): min(0), max(100), currentGuess(50) {}
         int getBestGuess() const {return currentGuess;}
         void updateGuess(bool toLow) {
             if (toLow) {
                 int newGuess = currentGuess + (max - currentGuess)/2;
                 min = currentGuess;
                 currentGuess = newGuess;
             }
             else {
                 int newGuess = min + (currentGuess - min)/2;
                 max = currentGuess;
                 currentGuess = newGuess;
             }

         }
};

This way you isolate the variables that are associated with guessing, so they are not accidentally modified by external code.
Issues
There seems to be an issue with your tests. You are both testing the actual value then asking for user input to confirm what you actually know.
    if (num < guess) {
        // Why are you asking this question.
        // You already know that the num is less than guess.
        // Are you trying to automate the processes or trying to
        // get user input to direct the action?
        std::cout << "Is this number lower than " << guess << "? (0 - false, 1 - true)\n";
        std::cin >> lower;

        // We know it is lower.
        // but you only update things if the user confirms.
        // if you get it wrong does this upset the program?
        if (lower) {
            upper = false;
            max = guess;
        }

Code Review:
You don't check if the input is valid:
    int num;
    std::cin >> num;

When accepting user input, always validate that you got something valid. Otherwise you will end up with the application locking up or going into an infinite loop. In this case the stream simply sets itself as bad when invalid data is input, which can be detected with if ()
   if (std::cin >> num) {
        // Read worked we have a number in the variable.
   }

Note: This will validate things like 54XX as good, since the first part is a valid number.  You may want to check the whole line to make sure it is just a number:
bool getValidNumberFromUser(int& num)
{
   std::string userInput;
   std::getline(std::cin, userInput);

   std::stringstream userInputStream(userInput);

   if (userInputStream >> num) {
        // Succesfully read a number.
        // but there should be no other trash on the line.
        // so let us validate that we got just a number.
        char garbage;
        if (userInputStream >> garbage) {
            // we got some garbage so there was an error on
            // user input. Lets return false from this function.
            return false;
        }
        // If we got here not garbage.
        return true;
   }
   // If we get here the user input did not even start with a number
   // So let us fail.
   return false;
}

bool isNumberOutOfRange(int number)
{
    return number < 0 || number > 100;
}

int getNumberFromPlayer()
{
    std::cout << "Enter number from 0 -> 100\n";

    int playerNumber;
    while(!getValidNumberFromUser(playerNumber) || isNumberOutOfRange(playerNumber)) {
        std::cout << "You entered an invalid number. Try Again\n";
    }
    return playerNumber;
}


As you say, this is wrong. This

Integer[] random = {6, -4, 12, 0, -10};
List<Integer> list = new ArrayList<Integer>(Arrays.asList(random));
Collections.sort(list);
Integer[] array = list.toArray(new Integer[list.size()]);

could be replaced by

Integer[] random = {6, -4, 12, 0, -10};
List<Integer> list = Arrays.asList(random);
Collections.sort(random);

where Arrays.asList just wraps the array without making a copy. Even better would be

Integer[] random = {6, -4, 12, 0, -10};
Arrays.sort(random);

Also note that sorting something just in order to be able to use binary search once makes no sense.

Also note that

Integer[] random = {6, -4, 12, 0, -10};

uses objects wrapping the int, while

int[] random = {6, -4, 12, 0, -10};

would be much more efficient.


Perform sum of squared numbers without using for loop

There is a base case... it's the line if x > 0 {
compare to the for loop version
for x=input: x>0: x=x-1 {
findSquareSum(input,a,x) sets x=input
if x > 0 { is the condition check
findSquareSum(x-1, a, iteration) decrements x
also consider the modified fucntion
func findSquareSum(x int, a []int, iteration int) {
    var num int
    if x <= 0 { return }

    fmt.Scanf("%d", &num)
    if num > 0 {
        a[iteration-1] += num * num
    }
    findSquareSum(x-1, a, iteration)
}

now it should look more like the base cases we are to seeing. It should also be clear that this is equivalent to the askers version (unless my go syntax is wrong!)
similarly
func readTest(x int, a []int){
    var input int
    if x <= 0 { return }
    fmt.Scanf("%d", &input)
    findSquareSum(input,a,x)
    readTest(x-1,a)
}


Probably the proper way would be to pass it via constructor as this would allow you to choose which driver phpFastCache() should without interfering with your class. And thats commonly referred as dependency injection. You have to type hint on the phpFastCache() returned instance interface which is phpfastcache_driver.
This gives you two things, you can easily change underlying caching mechanism and still lock only to the instances that you know that implement methods you use in your class.

Then the constructor would look like this:

public function __construct(phpfastcache_driver $cache)
{
  $this->cache = $cache;
}

And the initialisation of the class as follows:

$myCache = new Cache(phpFastCache('files'));

or

$myCache = new Cache(phpFastCache('memcached'));

or whatever storage engine phpFastCache supports.

Edit:
I've noticed that you have static methods which do access non static property, you can not do that. Remove static from them.


High execution time on number partitioning program in Python 2.7

Indentation

Your code is indented using a mixture of spaces and newlines. In Python, the use of 4 spaces per indent level is preferred. While Python 2 allows for mixed indentation, PEP8 recommends these be converted to spaces exclusively. Your indentation format seems to have affected display of the following lines:

        partitions[start].extend(curr_partitions)
        prev -= 1
        pp.extend(curr_partitions)
    start += 1
return partitions

The resulting code does not run. I have cleaned up indentation for make_partitions:

from collections import Counter
compare = lambda x, y: Counter(x) == Counter(y)

def mp(n):
    partitions = {}
    curr_partitions = []
    start = 1
    while start <= n:
        partitions[start] = []
        partitions[start].append([start])
        prev = start - 1
        pp = []

        while prev >= start-prev:
            curr_partitions = []
            prev_partitions = partitions[prev]
            for p in prev_partitions:
                q = list(p)
                q.append(start-prev)
            does_exist_already = False
            for ppp in pp:
                if compare(q, ppp):
                    does_exist_already = True
            if not does_exist_already:
                curr_partitions.append(q)

            partitions[start].extend(curr_partitions)
            prev -= 1
            pp.extend(curr_partitions)
        start += 1
    return partitions

Partitions

The edited code produces the following output for n = 7:

{1: [[1]], 2: [[2], [1, 1]], 3: [[3], [1, 1, 1]], 4: [[4], [1, 1, 1, 1],[1, 1,
2]], 5: [[5], [1, 1, 2, 1]], 6: [[6], [1, 1, 2, 1, 1], [1, 1, 2, 2], [1, 1, 1, 3
]], 7: [[7], [1, 1, 1, 3, 1], [1, 1, 2, 1, 2], [1, 1, 2, 3]]}

It seems that partitions containing integers in the range n/2 < i < n are not included. Then, it is hard to see how final_partition_list could contain the correct partitions. And, checking small values of n:

n = 3, output = 1

n = 4, output = 1

n = 5, output = 1

n = 6, output = 1

etc.

Your code may not necessarily be broken, but simply a victim of incorrect conversion from mixed indentation to spaces only.


Deciding whether an anchor should be updated

About Exceptions
In general, exceptions should never be part of the anticipated program flow. Using exceptions to test conditions in the data, is wrong.
On the other hand, that is not what you are doing. You are taking an anchor/link from an HTML document, and I would expect that to always be a well-formed URL.
Additionally, a poorly-formed URL in the supplied context is not a program fault either, so propagating an exception is not useful. You will need to handle it somewhere else if you do.
My only suggestion is that you should be logging it somewhere... don't you need to know that you have HTML pages with broken links?
Concerns
You have some programming problems.... I am unable to tell if it is serious, it may be fine depending on your circumstances... consider:

if (!link.contains(replaceFrom) && !link.contains(replaceInto)) {
    return false;
}

... you return false if the link contains the replacement String, even if it also contains the to-replace string. Perhaps you should make the code just:
if (!link.contains(replaceFrom)) {
    return false;
}

As I say, there may be a business reason why you also need to check for the replaceInto, but, as it is at the moment, I believe you may be missing some replacements because the anchor contains both texts...
Style
You have the code:

final URL url;
try {
    url = new URL(link);
} catch (MalformedURLException e) {
    return false;
}

Code like this makes me itch ;-) , and not because of the return false, but because 'dangling declarations' of the url are a smell to me. Note that the type conditions can be simplified since they are boolean checks. Your try/catch code would be better written as:
try {
    final URL url = new URL(link);

    final String query = url.getQuery();
    final NodeRef documentNodeRef = getNodeRefFromQueryString(query);
    final QName type = nodeService.getType(documentNodeRef);

    return ContentModel.KnowledgeCentreDocument.QNAME.equals(type);

} catch (MalformedURLException e) {
    return false;
}

Note that the constant QNAME is not null, I assume, and that it's equals() method is presumably an equals-contract compatable implementation, which means it should return false for QNAME.equals(null);...


See if a specific resource exists in a Kubernetes namespace

Without knowing more about the kubernetes API that's hard to say, maybe you'd be more lucky on StackOverflow instead.

That said, if there's no explicit function to check, probably not.

Especially the status code 404 sounds like it would probably mean "not present", so this doesn't seem overly bad actually.

Is it intentional that all other ApiExceptions also return false?  If so, than there's no point to check for the 404.  If not, they should be thrown again.


It's not that hard.

Instead of sorting the cards, looping over them and skipping double results, let's convert them to a more useful format:

var bitmap = 0;

for(var i = 0; i < cards.length; i++)
{
    var value = cards[i].value;

    // set i+1 bit in the bitmap
    bitmap |= 1 << (value + 1);

    // if it's an ace, also set the low bit
    if(value === 12)
        bitmap |= 1;
}

Now, if there's a card of value i in your hand, the i+1 bit will be set in the bitmap. An Ace is treated as two cards with values 13 and 0.
Next, we scan the bitmap for 5 consecutive bits set, which is equivalent to 31 (1 | 2 | 4 | 8 | 16). We start with the highest straight, which is 9.
The lowest straight is 0, if there is no straight i is -1.

for(var i = 10; i--; )
{
    if((bitmap & 31 << i) === (31 << i))
    {
        break;
    }
}

The method works for games with more than 5 cards. Note that in any variant of Poker, 5 cards make a hand, so even in Omaha with 9 cards, 5 cards give you a straight.

Note: The method is roughly equivalent to creating a set (and checking for 5 consecutive elements). As you can see, with bit-wise operators it is much simpler to check for 5 consecutive cards.

Another note: There's a harder-to-understand but slightly faster method for testing a straight given the bitmap. I might add it later, but for now I think this method hard enough to understand for beginners.


Configuration class in C#, reading an INI file

General

This class can't be reused because the path to the ini file is hardcoded. Having a parameter string path and using it to load the configuration would be a better way.

LoadConfig()

I don't like the Console.ReadKey(bool) and I don't see why the method should be able to terminate the process. In addition passing 0 to the Exit() method indicates that the process completed successfully which seems wrong.

The line where you assign the key/values to the dictionary is too long and therefor hard to read.

IMO the caller of the code should do the logging and you should let the exceptions bubble up the line.

Checking if the file is locked will pretence that it is safe to read the file, but it could happen that just after the check the file is opened and locked.

GetConfigValueByKey()

It seems strange that a not found key only will be logged. A better way would be to just use the bool TryGetXxx style.

How I would do this:

I would add an overloaded public constructor which takes a string fileName parameter. I would then make the parameterless constructor internal and let it call the public constructor with the "resources/config/pitaya.ini" to simulate the former functionality.

I would validate the fileName parameter and would throw the expected exceptions.

I would just initialize the dictionary in the constructor and if an exception occurs I would let it bubble up.

Like so
public class ConfigHandler
{
    private readonly Dictionary<string, string> _configItems = new Dictionary<string, string>();

    internal ConfigHandler()
        : this("resources/config/pitaya.ini")
    { }

    public ConfigHandler(string fileName)
    {
        if (fileName == null)
        {
            throw new ArgumentNullException(nameof(fileName));
        }

        if (string.IsNullOrWhiteSpace(fileName))
        {
            throw new ArgumentException($"The parameter {nameof(fileName)} may not be empty or whitespace", nameof(fileName));
        }

        if (File.Exists(fileName) == false)
        {
            throw new FileNotFoundException("File could not be found.", fileName);
        }

        _configItems = File.ReadLines(fileName)
                           .Where(IsConfigurationLine)
                           .Select(line => line.Split('='))
                           .ToDictionary(line => line[0], line => line[1]);
    }

    private static bool IsConfigurationLine(string line)
    {
        return !line.StartsWith("#") && line.Contains("=");
    }

    public bool TryGetValue(string key, out string value)
    {
        if (key == null)
        {
            throw new ArgumentNullException(nameof(key));
        }

        return _configItems.TryGetValue(key, out value);
    }
}


PowerShell - Loop Through Nested Objects

I rejigged your code a little to make it tidier. I don't have PowerBI, so I haven't tested it, and I can't guarantee that I haven't done anything dumb.

I got rid of the nested loop. Note the -PipelineVariable ws. What that does is put the output of that stage of the pipeline into a variable called $ws, which we can refer to later. It means that we don't need to do $ws = $_.

-PipelineVariable is one of the "Common Parameters", and is available on many or most cmdlets. You can abbreviate it to -PV, by the way.

I also got rid of the intermediate array $myArray since it wasn't needed.

Install-Module -Name MicrosoftPowerBIMgmt

Login-PowerBIServiceAccount

Get-PowerBIWorkspace -Scope Organization -PipelineVariable ws |
    ForEach-Object { Get-PowerBIReport -WorkspaceId $_.Id } |
    ForEach-Object {
            [pscustomobject]@{
                workspaceId   = $ws.Id
                workspaceName = $ws.Name
                reportId      = $_.id
                reportName    = $_.Name
                reportUrl     = $_.WebUrl
             }
        } |
    Export-Csv "PowerBIWorkspaceReports.csv"


Implementing a zipwithindex predicate in prolog

sure:

zipwithindex(List1, List2) :-
   findall(E/I, nth0(I, List1, E), List2).

Edit - after Tudor' comment

bagof/3 it's much better than findall/3, as it doesn't introduce unwanted new variables. This can be of utmost importance when working with constrained variables - i.e. CLP(FD) or CHR


You could also create a route constraint that redirects or changes the routedata to "buy module".

http://msdn.microsoft.com/en-us/library/cc668201.aspx#adding_constraints_to_routes

http://www.jfarrell.net/2008/11/asp-net-mvc-authentication-strategies.html


I think that you're using comments unnecessarily. If you set a variable called fileNumber, the comment // get file number doesn't tell the reader anything new and only clutters the code.

// directory check
let pathExists() = Directory.Exists(serverDirPath)

// create directory
let createDir() =
    if not (pathExists()) then
        Directory.CreateDirectory(serverDirPath) |> ignore
createDir()

I don't see any reason to have createDir or pathExists as separate functions, since they're short and not reusable.

And as Daniel mentioned in a comment, the check is not actually necessary. So, I would simplify this code to just:

Directory.CreateDirectory(serverDirPath) |> ignore

// check if row exist
let rowCount =
    query{
        for row in db.Uploads do
        select row
        count
    }

// get file number
let fileNumber =
    if rowCount < 1
        then
            1
        else
            query{
                for row in db.Uploads do
                select (row.FileNumber + 1)
                head
            }

You can use headOrDefault here, to get rid of the first query:

// get file number
let fileNumber =
    query {
        for row in db.Uploads do
        select row.FileNumber
        headOrDefault
    } + 1

Also, you're not using any ordering in the query, are you sure the largest FileNumber is always going to be the first one?

let finalServPath =
    serverDirPath + @"\" + fileNumber.ToString() + extension

You can use Path.Combine() to concatenate parts of a path:

let finalServPath =
    Path.Combine(serverDirPath, fileNumber.ToString() + extension)


The nested loop under # render cells and measure column widths computes maximum cell width of each column. Using itertools.zip_longest to turn columns into rows lets you use max on them:

cell_widths = [[len(row.format_cell(x)) for x in range(len(row.columns))]
                for row in self.rows]
col_widths = list(map(max, itertools.zip_longest(*cell_widths, fillvalue=0)))


Stack implementation using linked list in C++

This is quite good, actually. I have one big comment, and a few relatively minor comments.

RULE OF THREE. Anytime you define a destructor, you want to make sure you define your copy constructor and copy assignment operators. The reason for that is the following:

StackLinkedList<T> stack;
stack.push(...);
stack.push(...);
{
    StackLinkedList<T> stack2 = stack;
    stack2.push(...);
    // <== stack2 deleted here
}
// <== uh-oh, stack2 deleted all the nodes, but stack still thinks
// it has valid objects that it's holding onto that it needs to delete too!

Your class is sorely missing:

StackLinkedList(const StackLinkedList& );

friend void swap(StackLinkedList&, StackLinkedList& );
StackLinkedList& operator=(StackLinkedList other) {
    swap(*this, other);
    return *this;
}

For more on why I suggest this way specifically, see what is the copy-and-swap idiom.

You didn't mention if you were using C++11 or not. If you are, you want the Rule of Five: you will also need to implement the move constructor and move assignment operator. For this class in particular, those two should be very short.

Other comments are minor.

Use of typename. There are places where you need to use typename and there are places where you don't. Just don't use it in those latter cases - it's just unnecessary. In your code, literally every usage of typename is redundant and can be omitted.

top(). The typical implementation of containers is to make operations as fast as possible. So for top(), that would mean not checking empty() - that's up to the user. Just simply return m_List->m_Val and note that it's just undefined behavior to call top() on an empty stack. If you disagree and want to throw an exception, that is of course perfectly reasonable as well - but this not the way to do it:

throw new std::string("Stack is empty");

You're throwing a std::string*. Anybody that catches it would have to delete it, otherwise you're leaking memory - and std::string* doesn't really convey information. If you look in <stdexcept>, there's a better choice of exception type: std::out_of_range. Standard practice is to throw by value, catch by reference. So that line would be:

throw std::out_of_range("Stack is empty");

#pragma once should be the first line in your file, you have it after a different #include.


Organize JavaScript for video player controls

This looks just fine to me.

Some very minor nitpicks:

Remove //console.log(chapterTime);
Consider removing the blank line after var statements, it does not add much
chapterTime could use a comment as to what those numbers express (I assume seconds)
I would probably write this

buttons.delegate('click', function () {
    var button_name =  this.ancestor().get('id'),
        chapter = button_name.slice(1);

        playChapter(chapterTime[chapter-1], this);
}, 'a');

as

buttons.delegate('click', function () {
        var chapter = this.ancestor().get('id').slice(1) - 1;
        playChapter(chapterTime[chapter], this);
}, 'a');

The color strings #999 and #666 have a meaning, I assume enabled/disabled, you could use properly named constants for these, declared on top
Only seldom use double newlines, they are vertical overkill

Still, all in all I like your code.


Consider having your APIs return a promise instead. By the looks of it, success indicates that it's a Q promise which means it should be able to do then. This means we can throw away the "outer deferred" and use the promise directly.

Both requests don't necessarily need to be in sequence. The second API call doesn't seem to require the first one other than the fact that it checks for uniqueness and bails out if not unique. You can fire both in parallel, with a minor tradeoff that it will fire 2 in all cases. But then, 2 in parallel vs 2 in sequence. Time-wise, I'd prefer the former.

If you have native promises available or are able to polyfill it, then use native instead. Also, instead of resolving to a boolean, use the promise state as your boolean. Resolve or reject accordingly.

Your code can then be simplified to:

var result = scope.CurrentUser.Surname.length > 0;

var uniquenessRequest = apiService.UniqueEmailCheck(scope.CurrentUser.PersonId, scope.CurrentUser.Email);

var existenceRequest = apiService.GetSelectetExistent(scope.CurrentUser.FirstName, scope.CurrentUser.Surname, scope.CurrentUser.DOB).then( response => {
  $scope.SelectExistent = response;
  return response;
});

return !result ? Promise.reject() : Promise.all([
  uniquenessRequest,
  existenceRequest
]).then(results => {
  var pass = response[0] && response[1].length > 0;
  return Promise[ pass ? 'resolve' : 'reject' ]();
});


Android sharing selected text to other apps

Honestly I believe you have answered this question yourself: The app works just fine.

From what I can see, you are using the intent exactly as you are supposed to. You are also using EditText properly. But, because you have come all the way here I guess you want to hear some suggestions/criticism as well so I have tried really hard to come up with something:

You're inconsistent in adding spaces to your code. The best practice is to use VariableType variable = something; but in three lines you are writing VariableType variable=something; which makes the code a little bit harder to read.
I don't think you need to temporarily store the selectionStart and selectionEnd variables. (If you think it looks cleaner to store them in temporary variables, then by all means continue to do so) This code would be enough:

String selectedText = et.getText().toString().substring(et.getSelectionStart(), et.getSelectionEnd());

Or if you think that line is too long,

String text = et.getText().toString();
String selectedText = text.substring(et.getSelectionStart(), et.getSelectionEnd());

Consider what would happen if there is nothing at all stored in the EditText, do you still want to start an intent even if the string is empty?


With only three different items I don't think there's much benefit from iterating through a list and instantiating the multi-selects automatically. Your version IMO is much more legible than a version iterating through an embedded data structure. Although with lots of selects this could change fast.

You could take the approach of specifying the attributes of the selects (header, noneSelectedText etc.) as data attributes on the HTML. Then you could wire up your jQuery multiselect code to read the information from the selects themselves. So your jQuery would only have to specify the type of select to trigger the multiselect call on and you could add as many as you like without having to update your scripts.

So something like this:

<select class="dynamic-multiselect" data-header="Choose only One item!" data-none-selected-text="Select an Option" ...>
    <option ...>
    ...
</select>

<select class="dynamic-multiselect" data-header="Pick Any"  ...>
    <option ...>
    ...
</select>
...

And the Javascript would simply be:

$('.dynamic-multiselect').multiselect();


Return Data and Update Row without Multiple Lookups?

You could do it all in one step, like this.

CREATE PROCEDURE dbo.IncrementArtViews (@Slug varchar(250)) AS

UPDATE a
SET ArtViews = ArtViews + 1
OUTPUT a.ArtID, a.ArtUserID, a.ArtTitle, a.ArtHtml, a.ArtDescription,
 a.ArtKeywords, a.ArtLicenseID, l.licTitle, a.ArtViews, a.ArtCreated,
 a.ArtUpdated, s.SubID, s.SubTitle, c.CatID, c.CatTitle, sec.SecID,
 sec.SecTitle, u.UsrDisplayName AS UserName
FROM dbo.Article a
 INNER JOIN dbo.Subcategory s ON a.ArtSubcategoryID = s.SubID
 INNER JOIN dbo.Category c ON s.SubCatID = c.CatID
 INNER JOIN dbo.[Section] sec ON c.CatSectionID = sec.SecID
 INNER JOIN dbo.[User] u ON a.ArtUserID = u.UsrID
 INNER JOIN dbo.License l ON a.ArtLicenseID = l.LicID
WHERE a.ArtSlugHash = CHECKSUM(@Slug)
 AND a.ArtSlug = @Slug
 AND a.ArtApproved = 1


Python merge sort for a list containing distinct values

To address your immediate concern, yes it is a merge sort.

The naming is quite unusual. The procedure you call merge does the merge sort, and should be called so. The merge phase of the merge sort is done by the

    while i != length_firstHalf and j != length_secondHalf:

loop and the subsequent return. It is advisable to factor it out into a standalone merge procedure. OTOH I don't endorse a complicated return expressions.
It is unclear why do you limit yourself to the distinct values. The second if clause may be safely made into an else, and there is no more worries. Notice that your first comparison firstHalf[i] > secondHalf[j] is the way to handle duplicates.
Computing half doesn't belong to the base case.
As a nitpick, length == 1 or length == 0 is a long way to say length < 2.


Calculate the sum of all primes less than 2,000,000 in Swift

This is a bit of a brute-force solution using trial division, with an optimization that you try dividing by just the previously discovered primes.

When you want to find many primes, though, a much faster algorithm is the sieve-of-eratosthenes.


Reduce database touches for one to many data pull

A single query could be used to get all results. This would require formatting the results differently...
The table consumables_products could be added as a (n INNER) JOIN.
JOIN consumables_products P on P.uid = A.product_id --or is it B. product_id instead of A.uid??

The implicit join on consumables_consumables could also be written in a similar fashion.
$results = $this->db->all("SELECT P.uid as productUid, P.description as productDesc, A.*, B.description
    FROM consumables_product_consumables as A
    JOIN consumables_consumables as B ON B.uid = A.consum_id
    JOIN consumables_products P on P.uid = A.product_id
");

From there array_reduce() (or else a foreach loop) could be used to return the data in the specified format:
Note this is untested code...
return array_values(array_reduce(function($carry, $row) {
    $key = $row['productUid'];
    if (!isset($carry[$key])) {
        $carry[$key] = [
            'uid' => $row['productUid'],
            'description' => $row['productDesc'],
            'consumables' => []
        ];
    }
    $carry[$key]['consumables'][] = array_diff_key($row, array_flip(['productUid', 'productDesc']));
    return $carry;
}, []));

That array_flip(['productUid', 'productDesc']) could be stored in a variable outside the loop though it would need to be brought in using a use statement or if PHP 7.4+ is used then an arrow function could be used, which would allow use of that variable without the need for a use statement.
e.g.
$keysToUnset = array_flip(['productUid', 'productDesc']);
return array_values(array_reduce(function($carry, $row)  {
    ...
    $carry[$key]['consumables'][] = array_diff_key($row, $keysToUnset);
    return $carry;
}, []));

Also consider if all fields from consumables_product_consumables are needed. If not, select only the fields needed in order to minimized the returned data set.


Deque Container with an instant consumer for high speed object dumping

Ownership symantics:
void Container::Add_item(Some_object* obj)

Who owns obj?
This is a C-Style interface. Don't do it.
It would be better to pass in as unique_ptr. This shows transfer of ownership. Also with good compiler optimization is no more expensive than a normal pointer. This also results in slight modification in your code to make sure it handles ownership correctly.
Note: I would still use: std::deque<Some_object*> my_container;
Lockless queues
Lock are very expensive (relatively to queue management). There is a concept of thread safe lock-less queues.
If you have a very high frequency modification to the queue then that is something I would look into. see How do I build a lockless queue?


A VBA Product Dictionary with a Collection of Product Services

You seem to be misunderstanding how to use a Scripting.Dictionary.
There is no need to sort the data before processing into a dictionary.
There is also no need to construct a collection before you add to the dictionary.
Its also slightly more sensible to write the sub as a function.
As a final tweak I'd pass the array in as a parameter rather than hardwiring it into the function, but I'll leave that as an exercise for the reader (smile)
Public Function BuildTMProductDictionary() As Scripting.Dictionary

    Dim tmData As Variant
    tmData = Sheet1.ListObjects("Table1").DataBodyRange.Value

    Dim myDict As Scripting.Dictionary
    Set myDict = New Scripting.Dictionary

    Dim i As Long
    For i = LBound(tmData, 1) To UBound(tmData, 1)

        Dim myProduct As String
        myProduct = tmData(i, 1)

        Dim myService As String
        myService = tmData(i, 2)

        If Not myDict.exists(myProduct) Then

            myDict.Add myProduct, New Collection

        End If

        myDict.Item(myProduct).Add myService

    Next

    Set BuildTMProductDictionary = myDict

End Function

Replace
   If Not myDict.exists(myProduct) Then

        myDict.Add myProduct, New Collection

    End If

    myDict.Item(myProduct).Add myService

with
    If Not myDict.exists(myProduct) Then

        myDict.Add myProduct, New Scripting.Dictionary

    End If

    If Not myDict.Item(myProduct).exists(myService) Then

        myDict.Item(myProduct).Add myService,myService

    End If


Updating all members of a struct in database

One way you can simplify this code and also make it more forward compatible with future addition of new fields is by using a simple array that stores the register keys, database field names and a pointer to a function that transforms the register value in the adequate way. You should also be able to remove all duplicate code in the process.

The following example uses auto and C++11 lambdas to keep everything close together, but you can easily replace that by plain functions if you don't have access to a C++11 compiler. Also note that I don't have enough context to pick more meaningful names other than commands and xform, but you should be able to find better ones.

void FpgaAdapter::UpdateCpGsmDelayTime()
{
    auto xform1 = [](Uint32 regValue) {
        return static_cast<Uint32>(regValue * 6.51);
    };

    auto xform2 = [](Uint32 regValue) {
        const float tmp = (0xff & regValue) * 32.55;
        return (0xff & (regvalue >> 8)) * 1000 + static_cast<Uint32>(tmp);
    };

    static const struct {
        Uint32 regKey;
        const char * dbField;
        Uint32 (*transform)(Uint32);
    } commands[] = {
        { 0x98, "t14_cp",    xform1 },
        { 0x99, "T14_au",    xform1 },
        { 0x9c, "Tdl_fib_f", xform1 },
        { 0x9d, "Tul_fib_f", xform1 },
        { 0xa0, "Tdl_cp_f",  xform2 },
        { 0xa1, "Tul_cp_f",  xform2 }
    };

    for (int i = 0; i < sizeof(commands) / sizeof(commands[0]); ++i) {
        Uint32 regValue = 0;
        if (ReadReg(commands[i].regKey, regValue)) {
            const Uint32 result = commands[i].transform(regValue);
            SetStructElementToDB("CpGSMTimeDelayQuery", commands[i].dbField, result);
        }
    }
}


Graph implementation in c++ using adjacency matrix

Avoid using namespace std;.

Why are you using raw pointers?  Use smart pointers, or (better yet) standard containers like std::vector.  Since vector constructs its elements, much of your initialization code can be eliminated.

Make use of the member initializer list in your constructor.  There's no real difference with fundamental types like int, but with more complicated objects it can be a big help or outright necessity (to initialize a reference).

    Graph(int value): value(value) {

(That will initialize the member value with the parameter value.)  Then get rid of the this->value = value line.

Define variables as late as possible, with their first use if possible.  Make use of this in your for statements.

for (int k = 0; k < value; ++k)

In newEdge, your parameter validation accepts 0 as a valid edge index, but you then subtract one from it for the subscripting, resulting in Undefined Behavior and a possible crash.

display and isPath should be const (void display() const.  isPath does not validate its parameters like newEdge does.


Update bitmap in picturebox with data from a socket

If your blocks don't change size, why not create adjacent picture boxes so that you update each one individually?

If that isn't providing enough performance, remove the picture box altogether and create a custom user control where you override the OnPaint method and do your drawing inside of it.

This way, the you will pass your user control an array of bitmaps to draw and where to draw them and, when OnPaint gets called, you simply use DrawImage() to place each one at the appropriate location.

No need for you to join the bitmaps manually.

Should a new a image arrive and you want to force redrawing, simply call Invalidate() on the user control which will force OnPaint to be called.
This can be optimized even further as Invalidate can be called only on a specific region of your control, allowing you to only redraw the parts that are necessary.


Eliminate nested HTML elements for jQuery animation?

I honestly don't know if this will work properly in all browsers (read: I doubt it), but you could conceivably animate the text-indent property to oscillate between +n and -n.

Here's a quick, quick hack based loosely on jQuery UI's own shake effect.

Again, though, I have no idea if this will work any better. It seems pretty neat, but I have a suspicion it won't be as robust as using a <button> with nested elements.


You could use a recursive function to traverse your object and generate the HTML.

Something like:

function generateList(items, depth) {
    if (!depth) depth = 0;
    var ul = new Element('ul');
    if (depth) { ul.addClass('here' + depth); }
    for (var i = 0; i < items.length; ++i)
    {
        var item = items[i];
        var li = new Element('li').inject(ul);
        if (item.items) {
            li.adopt(new Element('span', {
                'html' : item.title,
                'class': 'pgTitle'
            }));
            li.adopt(generateList(item.items, depth + 1));
        } else {
            li.adopt(new Element('a', {
                'href' : item.href,
                'title': item.title
            }));
        }
    }
    return ul;
}

if (itemLi.items) {
    generateList(itemLi.items).inject(el);
}

This doesn't include code to add the page spans, cause i don't understand yet how they should be generated.  (The code doesn't include declarations of the variables involved, for starters.)  But it should generate a list of links, with sublists for any items that have sub-items.  The classes for the sublists are kinda unnecessary -- CSS can select them just fine as ul>li>ul and ul>li>ul>li>ul -- so unless you have some other need to track the amount of nesting, you could get rid of depth and the class on the uls.


Creating folders even if already exist or removing removing their content

The second one is definitively safer, since in the first one you actually remove everything in all subfolders of directory, not just in the three folders you want to remove.

Some additional comments:

I would save the result of os.path.join(directory, folder) in a variable, you calculate it like three times.
Have a look at Python's official style-guide, PEP8. It recommends using lower_case both for variables and for function names, so your function should be called clean_folders.
A bare except is basically never a good idea. And even worse is a bare except with the unhelpful message 'something went wrong'. You want to either catch the exception you are looking for and handle it, or let the exception bubble to the top and halt the execution of the program. So, find out what kind of exception you actually want to catch (maybe IOError?). Or at least use except Exception, which excludes exceptions like e.g. the user pressing Ctrl+C being caught.


Add two signed integers, given in stdin(space separated) in i386 ASM Linux ABI

You are asking for a code review, and my first bit of feedback is: COMMENTS.

Please, reading raw assembler is a challenge.  Start by a comment block at the top that describes the purpose of the code, then consider line-by-line comments, something like this: https://codereview.stackexchange.com/a/156947/110050


Efficiently swapping the first and last five bits in an unsigned 16-bit integer in C

Programming 8-bitters in C is tricky, particularly when dealing with antique ones like Z80. The things you absolutely must consider are:

Keep to 8 bit arithmetic whenever possible.
Ensure that no bitwise arithmetic is done on signed int types. This means that you need to understand the common Implicit type promotion rules of C.
32 bit arithmetic should be avoided like the plague. And let's not even mention floating point.

If you don't keep the above in mind, then the theoretic efficiency of the algorithm be damned. Thus you cannot allow a PC programmer to design it, because they don't understand how an 8-bit MCU works.

Regarding your posted code:

It suffers from using lots of 16 bit arithmetic, that the compiler cannot likely optimize well.
((flash[idx + 1]) << 8); invokes undefined behavior, if flash is an uint8_t with the MSB set. This is a bug caused by implicit integer promotion to int.
Using signed hex literals on a 8/16 bit MCU is dangerous, because up to 0x7FFF they are of type int, but above that they are of type unsigned int. Therefore, you should make a habit of always appending an u/U suffix to them.

Assuming that flash is an array of const uint8_t corresponding to something in flash memory, and assuming that the 6 middle bits should be preserved, not zero-out, then you should do something like this:

// assuming Z80 Little Endian:
uint8_t lo = flash[idx];
uint8_t hi = flash[idx+1];

uint8_t lo_shift = (lo & B_MASK) << 3;
uint8_t hi_shift = (hi & R_MASK) >> 3;

lo = (lo & 0xE0u) | hi_shift;
hi = (hi & 0x07u) | lo_shift;

uint16_t color = ((uint16_t)hi<<8) | lo;

This will allow the compiler to perform as much arithmetic as possible on 8 bit integers. There are implicit promotions to int, but such promotions are not dangerous, as we don't shift data in/out of the sign bit of a 16 bit int. And the u suffix will kill off any accidental promotions, since it guarantees uint16_t in case of 16 bit arithmetic.

To get rid of "magic numbers":

#define R_MASK 0xF8u
#define B_MASK 0x1Fu

uint8_t lo = flash[idx];
uint8_t hi = flash[idx+1];

uint8_t lo_shift = (lo & B_MASK) << 3;
uint8_t hi_shift = (hi & R_MASK) >> 3;

lo = (lo & (uint8_t)~B_MASK) | hi_shift;
hi = (hi & (uint8_t)~R_MASK) | lo_shift;

uint16_t color = (uint16_t)hi << 8 | lo;


Find the minimum path sum in a binary tree

There's no docstring. What kind of thing is a TreeNode? What does the min_path method do? What should I pass for each of the parameters?
The code is written in Python 2.7, which is obsolescent (it gets bug fixes but no new features). We'll see later that this causes inconvenience because of the lack of the nonlocal statement. I suggest switching to Python 3.
The duplicated code for pushing and popping the prefix list, and updating sum_so_far, can be avoided, like this:

def min_path(self, sum_so_far, prefix, result, result_path):
    prefix.append(self.value)
    sum_so_far += self.value
    if self.left:
        self.left.min_path(sum_so_far, prefix, result, result_path)
    if self.right:
        self.right.min_path(sum_so_far, prefix, result, result_path)
    if not self.left and not self.right: # leaf node
        if sum_so_far < result[0]:
            result[0] = sum_so_far
            if len(result_path) > 0:
                result_path.pop(0)
            result_path.append(prefix[:])
    prefix.pop(-1)

The duplicated code for visiting the children can be avoided, like this:

children = [c for c in (self.left, self.right) if c]
if children:
    for child in children:
        child.min_path(sum_so_far, prefix, result, result_path)
else: # leaf node
    # etc.

But a better approach would be to use a locally defined function, like this:

def min_path(root):
    """Return list of values on the minimum path from root to a leaf."""
    min_path = []
    min_sum = [float('inf')]
    prefix = []

    def visit(node, sum_so_far):
        prefix.append(node.value)
        sum_so_far += node.value
        children = [c for c in (node.left, node.right) if c]
        if children:
            for child in children:
                visit(child, sum_so_far)
        elif sum_so_far < min_sum[0]:
            min_sum[0] = sum_so_far
            min_path[:] = prefix[:]
        prefix.pop(-1)

    visit(root, 0)
    return min_path

This still uses the trick of updating the first element of a list in order to update a result inside a possibly nested function call, but at least here the trick is hidden inside the implementation, and not exposed to the caller.

(In Python 3, you could write nonlocal min_sum and so avoid the need for the trick.)
Alternatively, you could use the stack of iterators pattern. This avoids making recursive function calls, and so there's no difficulty in maintaining the running minimum.

def min_path(root):
    """Return list of values on the minimum path from root to a leaf."""
    min_path = []
    min_sum = float('inf')
    current_path = [0]
    current_sum = 0
    stack = [iter([root])]
    while stack:
        for node in stack[-1]:
            current_path.append(node.value)
            current_sum += node.value
            children = [n for n in (node.left, node.right) if n]
            stack.append(iter(children))
            if not children and current_sum < min_sum:
                min_sum = current_sum
                min_path = current_path[1:]
            break
        else:
            current_sum -= current_path.pop()
            stack.pop()
    return min_path


Here are a few comments:

you don't seem to be using any instance fields/methods of the enclosing class. So it seems that you could make the method static
throwing Exception is not ideal - you should only throw the specific exceptions that the code can throw
finally the method does several things and you could extract each step in its own method

An initial refactoring could therefore look like:

private static String getURL(FlowType type) throws SpecificException {
  StringBuilder url = new StringBuilder();

  url.append(getUrlRoot(type));
  url.append("web/hasChanged?ver=");
  url.append(getVersion(type));

  return url.toString();
}

private static String getUrlRoot(FlowType type) {
  if (TestUtils.isProduction()) {
    return type == FlowType.HOLDER ? VISITOR : USER;
  } else {
    return type == FlowType.HOLDER ? VISITOR_STAGE : USER_STAGE;
  }
}

private static long getVersion(FlowType type) {
  if (DataMapping.isInitialized()) {
    Partition partition = DataMapping.getPartition(type);
    if (!TestUtils.isEmpty(partition)) return partition.getVersion();
  }
  return 0;
}

That leaves one code smell which is that you seem to access a lot of "static state" via the TestUtils and DataMapping classes. Without knowing what they do it's hard to tell if this is good or bad (likely: bad).

The getUrl method should probably not need to know that these static methods exist so I would try to remove the calls and pass the required information as an argument of the getUrl method.


Python program to find the most frequent letter in a text

If you are going to use the collections module at all (as you did for collections.defaultdict), then why not use collections.Counter, which offers a most_common() method?


Compiler errors

First of all, this code does not compile with the (IMO too lenient) command line of :

gcc -Wall -Werror main.c -o strtol

Instead it gives the message that @vnp showed in their answer, that you should change if (number[0] = '0') to either if ( (number[0] = '0') ) or to if (number[0] == '0').

Having said that, the command line I usually use (and the one I put in my Makefiles) is:

-Wall -Wextra -Wfloat-equal -Wundef -Werror -fverbose-asm -Wint-to-pointer-cast -Wshadow -Wpointer-arith -Wcast-align -Wstrict-prototypes -Wcast-qual -Wmissing-prototypes -Wstrict-overflow=5 -Wwrite-strings -Wconversion --pedantic-errors -std=gnu11 -ggdb

With these arguments I get the following from my IDE:

error: conversion to ‘int’ from ‘size_t {aka long unsigned int}’ may alter its value [-Werror=conversion] at line 15 col 24

error: using the result of an assignment as a condition without parentheses [-Werror,-Wparentheses] at line 45 col 9

note: place parentheses around the assignment to silence this warning at line 45 col 19

note: use '==' to turn this assignment into an equality comparison at line 45 col 19

Without fixing these, the program does not work quite correctly:

$ ./strtol
4
Your number is: 0
Press any key to continue...

$ ./strtol
888
Your number is: 0
YOUR NUMBER IS: 88
Press any key to continue...

$ ./strtol
11
Your number is: 0
YOUR NUMBER IS: 1
Press any key to continue...

Upon further inspection, the first character is ignored in the output:

$ ./strtol
623642
Your number is: 0
YOUR NUMBER IS: 23642
Press any key to continue...

$ ./strtol
 435345345
Your number is: 0
YOUR NUMBER IS: 435345345
Press any key to continue...

Upon correcting the errors mentioned by the compiler flags, however, the bugs appear to have disappeared!

$ ./strtol
4545
YOUR NUMBER IS: 4545
Press any key to continue...

$ ./strtol
 90
YOUR NUMBER IS: 90
Press any key to continue...

$ ./strtol
asdasdasdadasdasd
STRING FAIILED TO CONVERT...
Press any key to continue...

$ ./strtol
9999999
YOUR NUMBER IS: 9999999
Press any key to continue...

Let this be a lesson to ye -- listen to the C compiler, for it knows many things :)

API

When I write in C, I try to make my functions applicable to a wide variety of uses because C is verbose, simplistic and lacks polymorphism.

Having said that, I'm not sure how I feel about the interface I find when I read your code. Because the point of this program is hardly an end unto itself, surely this has applications in other projects' #includes.

To this end, it would likely be best and most testable if functions didn't have rather unrelated side effects, like printing, which could be handled by the caller.

That is, however, quite subjective and your use-case may differ entirely.

Organisation / Style

I know you're using Windows because you call getch() without an #include <curses.h>, or perhaps that was a typo and you meant getchar() (from <stdio.h>).

So even though all the functions in windows.h are laughable with their longCamelCaseCOMNames, "idiomatic" C uses snake_case_ndrscrs_and_abbrs, not camelCase.

Moreover, in "idiomatic" modern C:

#include <stdbool.h> gives us the much cleaner while ( true ) { ...
a function purporting to call strtol (string to long int) should have type long, not int
code uses the bool or ssize_t return type, or writes error to a pointer passed as an argument,  to indicate error rather than 0

this way, I don't have to have two if statements every time I want to use your function -- this is almost as bad as atoi.

always use braces around if statement bodies -- okay, maybe this is personal preference but I think it misleads me and other people reading your code.

How I would write it

I've been writing a lot of C lately, so here's how I'd reimplement your idea.

Mine writes a lot less STDOUT, but you could make it do more with the information the functions give you:

#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>

#define MAXLENGTH 1024

bool    readln (char** buf, const size_t len);
char* conv_str (const char* const str, long* out);
void str_chomp (char* const str);

// read a line of STDIN
bool readln (char** buf, const size_t len) {

  if ( fgets(*buf, len > INT_MAX ? INT_MAX : (int) len, stdin) != NULL) {
    str_chomp(*buf);
    return true;
  }
  return false;

}

// try to convert a string to a number or return the erroneous part
char* conv_str (const char* const str, long* out) {
  char* end   = NULL;
  long number = strtol(str, &end, 10);

  if ( end != str && !(*end) ) {
    *out = number;
    end = NULL;
  }

  return end;
}

// cut the last newline or don't
void str_chomp (char* const str) {

  if (str && (strchr(str, '\n') != NULL) ) {
    str[ strcspn(str, "\n") ] = 0;
  }
}

int main(void) {

  char* in_buf = malloc(sizeof (char) * MAXLENGTH);

  printf("Enter a number! ");

  while ( ! readln(&in_buf, MAXLENGTH) ) {
    printf("\nEnter another! ");
  }

  long out;
  char* err = conv_str(in_buf, &out);
  if ( err == NULL) {
    printf("Your number was: %ld\n", out);

  } else {
    fprintf(stderr, "That number '%s' was junk!\n", err);
  }

  free(in_buf);
  return EXIT_SUCCESS;
}


PHPmailer sanitazion/validation a second oppinion.

and welcome to CodeReview!

Here's a few things:

You have a lot of pointless comments

("includes": The includes are the next line. We see them; no need to tell us.)

Indent block content.

Whenever you enter an if block, indent it.
Same for while/for/functions/classes/methods/etc

Your variable-variable loop is equivalent to extract.
extract tends to be a bad idea (the manual has various warnings)

It pollutes the scope
You no longer know what variables are and are not defined unless you strictly control what is inside of the array (which you don't for $_POST)
Users can clobber your values, meaning there are certain security implications.
Can be mitigated with options to extract, but still a problem
In short, there are a few situations where extract is convenient and a decent idea; this is not one of them.
use $_POST[...] or $entries[...] directly.

Variable variables are also a bad idea.

Variable variables scream "What I really need is an array!"
You already have an array :)

Don't sanitize content until you're actually ready to put it into the context for which you're sanitizing it.

For example, & is a special character in HTML (in some contexts). DBs do not care about it. Nor do plain text emails. Or email subjects. Or... infinite things.
Rule of thumb: sanitize at the last possible moment.
You can also take the raw value and process it, but you can't always do the reverse.

Be careful with empty() on strings

empty($var) === (isset($var) && $var)
Implicit bool rules are very odd in PHP though. In particular, the string "0" can get you.
I doubt 0 should be a valid email content, but just throwing it out there in case it gets you in the future.

Invert your conditions and you'll see that you can bail early:

if (...) { /* huge block / } else { / redirect / exit; }
Instead you could do if (!...) { / redirect */ exit; }
Now your entire file doesn't have to be indented one step.
This is similar to the concept of returning early, though it tends to be less applicable to files (redirection is one of the few justified uses of exit in web site PHP)

You have a typo of $contact_Mame rather than $contact_Name in your email content
Be careful with 500 errors. IE has a minimum length limit where if your response is less than some number of bytes, IE 'helpfully' replaces your content with its own.

Also, I'm torn on how I feel about this being a 500 response. It's not really an internal error so much as just an exception.
Internal errors implies a major mess up to me like Apache is pissed off, or a E_FATAL PHP error.

You should probably log the email failing to send. You could just use something like trigger_error if you want to go the simple route.
$formOK is gaurenteed to be $formOK === empty($errors). This means you could just use empty($errors) in it's place.
I tend to use only strict equalities with strings these days. If you're comparing something to a string, you're sure 99.9% of the time that it's a string. If you're sure it should be a string, might as well use a strict check.

There are situations where loose string comparisons are still quite handy though.

I would use a GET or POST variable to signify AJAX rather than checking a header.

Headers can be spoofed.
Testing becomes easier.
No potential browser/JS library compatibility issues

$mail->Subject = "$contact_Subject"; is (functionally) equivalent to $mail->Subject = (string) $contact_Subject;

You know it's already a string, so no need for the cast.
Just do $mail->Subject = $contact_Subject.
Also, I wouldn't use "$var" as a cast. I would stick with explict casts ((string) $var).


I think this is suggesting roughly (maybe exactly) the same technique as @harold does in his answer, but I'm not entirely certain that I understand his answer, so I can't say with certainty whether it's the same or not.

I'd consider two facts in coming to an answer. First, that where two bits are identical, we don't need to do anything to swap them--i.e., swapping a 1 with a 1 or a 0 with a 0 doesn't change anything.

Therefore, we only need to do anything where the bits are not equal to each other. In this case, we have to flip both bits--i.e., the one that was a 0 has to become a 1, and the one that was a 1 has to become a 0.

At least to me, that immediately brings an exclusive-or to mind. An exclusive-or produces a 1 if one input or the other (but not both) is a 1. Looking at it slightly differently, it produces a 1 if the bits are not equal to each other, and a 0 if they are equal to each other. Looked at from yet a slightly different angle, an XOR with 0 leaves a bit unchanged, and an XOR with 1 always flips the bit (changes a 0 to a 1, or a 1 to a 0).

With that in hand, the job becomes fairly simple: we start by XORing the bits in the two ranges. This gives us 0s where they contain identical bits (meaning we want to leave them unchanged). It gives us 1s where they contain differing bits (meaning we want to flip the bits in both ranges).

We then XOR that mask with the bits in each range. That leaves the bits in each range unchanged where they were identical to start with, and flips the bits in each range where they were different.

For example, let's consider swapping the first 4 bits of a byte with the second 4 bits:

first four: 0 1 0 1
last four:  0 1 1 0

When we XOR these, we get:

mask:       0 0 1 1

We then XOR that back with each of the input ranges:

first four: 0 1 0 1
mask:       0 0 1 1
result:     0 1 1 0

last four: 0 1 1 0
mask:      0 0 1 1
result:    0 1 0 1

And now the first four have the same values as the last four did to start with (and vice versa).

Looking more specifically at your code, it has a fair number of places I think it could be made simpler and probably shorter. You start by reading four numbers, each with a block of code like this:

while (true)
{
 // input number

    Console.WriteLine("Input n:");
    if (uint.TryParse(Console.ReadLine(), out n))
    {
        if (n >= 0)
        {
            break;
        }
    }
}

The only things that change from one of these to the next are the string you display and the identity of the variable you're reading. This is an ideal candidate for being turned into a function. The function needs to read a number (just as you've done it above) and return the value when it's successful. Then the code in main will just call that function for each of the numbers it needs to read:

n = read_number("Input n:");
p = read_number("Input p:");
q = read_number("Input q:");
k = read_number("Input k:");

It's probably possible to avoid having to pass the string as well--you'd pass the variable itself, and figure out the name of that variable using reflection to build your string. That takes some rather more advanced use of .NET though, and I wouldn't advise it for now.

When it comes to finding which range is first:

if (p>q)
{
    num1 = q;
    num2 = p;
}
else
{
    num1 = p;
    num2 = q;
}

I think I'd just use p and q, but swap them if they're out of order:

if (p>q) {
    temp = p;
    p = q;
    q = temp;
}

(...and wish you were using C++, so you didn't have to re-implement basic operations like this for the 4 billionth time).

I've already advised a complete rewrite of the swapping code itself, so I guess there's not much point in reviewing that part of your code.


When possible, use an initializer list:

Node() : rightNode()
{ }

I don't think you're using C++11, but in case you are, use nullptr.

Giving Node a full constructor would be very advantageous for simplifying a lot of boilerplate code.

For example, everything like:

Node<T> *temp = new Node<T>();
temp->data = data;
temp->rightNode = startNode;

Could become a one liner:

Node* temp = new Node(data, startNode);

Also, a proper constructor avoids the exception safety problem that user1703394 mentioned.

Just for reference, the Node with a constructor would look like:

struct Node {
    T data;
    Node *rightNode;

    Node(const T& val, Node* rightNode) : data(val), rightNode(rightNode)
    { }
};

Note that the member order was changed since it needs to match the initialization list order. Changing the order allowed the constructor to be more natural (since the constructor argument order should match the initialization list order).

In C++, it's much more common to see T* var rather than T *var. It's just a stylistic qualm, but something to be aware of.

You should have blank lines between your methods.

A non-constant operator shouldn't exist on a list. If you can't provide it in constant time, don't provide it. It's very non-standard, and it's misleading to a consumer of the class. Note that the idiomatic way to expose the data is via a forward iterator.

There's a grave lack of understanding of memory ownership in get. In particular, unless you want the ownership of the node to end, you should not be freeing it.

As a general piece of advice, whenever you have doubts about memory management, consider using something like valgrind.

Try to simplify your code down to a general case rather than having lots of special cases. As others have noted, a sentinel node can heavily simplify this. As a random note, if you do use a sentinel node, and you're concern about performance, try to not dynamically allocate it. That saves you an allocation on an empty list.

Is LinkedList actually ever going to be extended (as implied by the virtual destructor)? Considering all of the properties are private and none of the methods (other than destructor) are virtual, there's not really a meaningful way that you can extend it.

Don't use the implicit private visibility of classes. Everything should be in either a public, private, or protected block. (There's nothing technically wrong with it of course, it's just good to be consistent.) Note that this doesn't apply to structs. Structs are almost always only public, so there's no potential confusion.

Be mindful of what can cause copies. In particular, get can cause an extra copy for no reason. T tempData = temp->rightNode->data; creates a copy, and then returning could, in theory--though never in practice--create a copy. If you just return directly, you can avoid a possible copy (though one will still have to happen).

Better yet, should get really be returning a copy? You could be returning either a reference or const reference (depending on if either a const or non-const version of get is called) so that the caller can modify the data, or so that a needless copy can be avoided in the read-only situation.

Your header stuff should have more spacing in it:

#ifndef LINKEDLIST_H_
#define LINKEDLIST_H_

#include <iostream>

using std::cout; // These should not be here!
using std::endl;

#endif /* LINKEDLIST_H_ */

The comment is just useless noise unless you have a lot of nested directives. Considering you only have one, this comment is useless. Also, most modern IDEs make these types of comments useless even if there are a ton of directives since they can highlight the counterpart. (I'm of the school of thought that even without highlighting, if there's enough levels for the comments to be necessary, something is very, very wrong with the the structure of the code.)

There's not a technical need to do so, but it's nice to try to be consistent with the standard library. This allows someone who is using your class for the first time to very intuitively pick up it's use. For example, I would expect size() rather than getSize(). I also might use pop instead of remove.

Sometimes an else clause is less confusing than a hidden return, especially in void functions. For example, the following is much clearer to me:

void pushFront(T data) {
    if (size > 0) {
        Node<T> *temp = new Node<T>();
        temp->data = data;
        temp->rightNode = startNode;
        startNode = temp;
        size++;
    } else {
        pushBack(data);
    }
}

I actually had to stop and pause for a long moment the first time I read through your code to make sure you weren't adding twice.

There are a lot of const correctness issues in your code. Please look into it. The short explanation is that any time something is only being read, it should be accepted by const reference.

Consider having each node own it's rightNode. This would mean that instead of a looping destructor, you could simple delete the head node and let the deletion cascade. This would work particularly well with a automatically allocated sentinel node since it would mean you could have a default destructor in the list.

Sized based looping on a linked structure is rather rare. The standard way to do it is to loop on the pointers. In the situations  you've used it though, the uses are arguably just as clear as the pointer case.

Consider keeping a tail pointer. That lets you push and pop to/from the end in constant time.


Performing several integer division operations on an array

Correctness. Technically the program is incorrect. The assignment requires the result to be printed once. Your solution prints out the state of array after each division.
Optimization. Since you only need to print the result once, you don't have to preform an actual division on each query. Accumulate the product of divisors, and perform the division once at the last step. Certain care to avoid overflow is necessary.

Most likely the program statement included restrictions on the input data. It would be nice to see them.


Solving the problem of using directives in a header file with a macro. Is this stupid?

You're writing a lot of code, but what is the benefit?  How is this any worse?

namespace MyNamespace {
    namespace ImplDetails {
        // Non-public code.
    }
    // Public code.
}

Yes, people can access things in ImplDetails, but you can't get around that sanely.  Obscuring namespace names is only going to hurt compatibility (when a namespace gets renamed after you insert a new one, which will happen eventually).  If people want to access your internals, they will.


Maximum subset sum with no adjacent elements

Many folks find that tacking on { } braces
to even a single-line if body is a useful way of preventing future bugs.

You wrote:

  array[0] + maxSubsetSumNoAdjacent(Arrays.copyOfRange(array, 2, array.length)),
  array[1] + maxSubsetSumNoAdjacent(Arrays.copyOfRange(array, 3, array.length))

The pair of copy statements is wasteful.
You're allocating temp storage (for GC to collect)
and consuming memory bandwidth.
It turns what could be a linear algorithm into a quadratic one (O(n) → O(n^2)).
The caller is going to simply hand you an array,
so you have to conform to that public API, accepting a single argument.
But nothing stops you from overloading, from writing a private helper.
Your public function should immediately ask the helper about the array,
from index 0 onward to end of array.
Then all the work happens in the helper.
Note that recursive calls that pass array plus a starting index
will never copy the array.
They merely pass a pointer to start of original array, in O(1) time,
independent of how enormous that array happens to be.
You have an opportunity to dramatically improve the implemented algorithm,
by passing index to the "as yet unsolved" portion of the array.


Efficient way to add a colon before and after every word in strings inside a Series

Both pandas.Series and pandas.Index have vectorized string additions. You can just do:

to_emojize = pd.Series(":" + coef_mat_emoji.index + ":")
coef_mat_emoji.index = to_emojize.apply(emoji.emojize, use_aliases=True)

Note that pandas.Series.apply passes any additional keyword arguments along to the function, so there is no need for the lambda here at all.

This will create an intermediate series from the first addition, which might not be the most memory efficient way to do this. But it is the easiest and most readable, so unless you run out of memory with this, this is what I would use.

Alternatively you could put it all into one apply call (Python 3.6+ for f-strings):

coef_mat_emoji.index = pd.Series(coef_mat_emoji.index).apply(
                        lambda x: emoji.emojize(f":{x}:", use_aliases=True))

You would have to timeit with your actual data to see if this is any faster. It might be that the call to emoji.emojize will dominate anyway.


As you noticed, this function is slow because it collects all the results before it starts printing them. To circumvent that problem, you need to interleave the collection of information and its printing.

A good way of doing that whilst keeping a compositional approach to solving the problem is to introduce a datatype reifying the structure of walkDir's call graph. Instead of sequencing all IO actions and getting a list of FilePaths back, you'd build a tree describing the computation (RTree for Rose Tree and T for Transformer as it takes an m):

data RTreeT m a = Node a [m (RTreeT m a)]

You can now write walkDir' describing your strategy to explore the directories on your filesystem: return the files present in the current directory immediately and then explore the subdirectories one after the other.

walkDir' :: FilePath -> IO (RTreeT IO [FilePath])
walkDir' r = do
  contents      <- fmap (r </>) . exceptLocal <$> getDirectoryContents r
  (files, dirs) <- filesAndDirs contents
  return $ Node files $ fmap walkDir' dirs

where filesAndDirs partitions a list of FilePath depending on whether they are files or directories (using tagDirectories to perform that test).

  tagDirectories :: [FilePath] -> IO [(FilePath, Bool)]
  tagDirectories = mapM (\ x -> (x,) <$> doesDirectoryExist x)

  filesAndDirs :: [FilePath] -> IO ([FilePath], [FilePath])
  filesAndDirs c = bimap (fmap fst) . partition (not . snd) <$> tagDirectories c
    where bimap f (a, b) = (f a, f b)

and exceptLocal is the filter you had in your original code snippet:

  exceptLocal :: [FilePath] -> [FilePath]
  exceptLocal = filter ((&&) . (/=) "." <*> (/=) "..")

You now have an RTreeT IO [FilePath] and you can described a strategy to print it which will interleave printing some of the content and running some of the remaining IO actions:

printRTreeT :: Show a => RTreeT IO a -> IO ()
printRTreeT (Node a mts) = print a >> mapM_ (printRTreeT =<<) mts

Of course, this is a rather crude printing function (e.g. you will notice quite a few empty lists if you have empty subdirectories) but it gives you an idea of how to proceed from there on.

If this is still slow, you may want to play the same sort of trick on filesAndDirs: rather than sequencing all tests in one go, you could want to have a structure allowing you to only deal with one FilePath at a time.


I would recommend a using modern Verilog header:

module prescaleMainCLK(
    input      CLK,
    output reg prescaledCLK
);

adding bit size to your constants is best practice. 'b0 for all zeros with auto sizing. 0 is an integer likely only 32 bits long which can get you in trouble if you start applying to regs bigger than than 32 bits.

The use of initial is only valid in FPGA synthesis, for ASIC you should use a active low async reset.

reg [3:0] counter;

initial begin
    // Initialise both variables
    counter      <= 'b0;
end

always @ (posedge CLK) begin
  counter <= counter + 1'd1;
end

Versus for ASIC:

always @ (posedge CLK or negedge rst_n) begin
  if(~rst_n) begin
    counter <= 'd0;
  end
  else begin
    counter <= counter + 1'd1;
  end
end

You can reuse the counter bits (as mentioned in another answer) for your slower clocks

wire clk_div2  = counter[0];
wire clk_div4  = counter[1];
wire clk_div8  = counter[2];
wire clk_div16 = counter[3];

At faster frequencies this often becomes tricky to balance clocks correctly. A standard industry practice would be to use enables (derived from this counter) for a clock gate. The clock gate allows a pulse from the faster clock through, you loose the 50 50 duty cycle of the clock but balancing the clock tress becomes much easier.


Writing a particular column of a two-dimension array to a worksheet

I wouldn't use

Option Base 1

It's completely unneeded, just change your loops to go from LBound to UBound. Remember, it's always better to stick with defaults otherwise you need to explain why you're doing it. Much easier -

For rowFirstArray = LBound(firstArray, 1) To UBound(firstArray, 1)

What's this for:

Dim previousSetting As Boolean
previousSetting = Application.DisplayAlerts
Application.DisplayAlerts = False
tempWS.Delete
Application.DisplayAlerts = previousSetting

You're turning it off no matter what anyway, there's no reason to store the setting. Why not just put it into an If block instead?

If Application.DisplayAlerts Then
    Application.DisplayAlerts = False
    tempWS.Delete
    Application.DisplayAlerts = True
    Else: tempWS.Delete
End If

I'm not sure what this is doing -

ReDim Preserve firstArray(UBound(firstArray, 1), UBound(firstArray, 2) + 1)

Usually you need to say 1 to UBound(...) for a dimension. But, you can't redimension the first dimension in a non- one dimensional array. So I'm not sure what is supposed to happen here.

Don't often see the Erase method

Erase secondArray

More commonly you set the array to nothing if you need to clean it up, but usually you won't need to clean it up.

Your With blocks aren't really needed

With ThisWorkbook.Worksheets(1)
    firstArray = .Range("A1", .Range("A1").End(xlDown).End(xlToRight))
End With

Can just be

firstArray = Sheet1.Range("A1", Sheet1.Range("A1").End(xlDown).End(xlToRight))

But I think what you mean is

firstArray = Sheet1.Range(Sheet1.Cells(1,1),Sheet1.Cells(lastRow, lastColumn))

What it's currently doing is

Range("A1") to (Rows.Count, 1)

The .End(xlToRight) isn't doing anything excepting the width of column A.

Dim rowFirstArray As Long
Dim rowSecondArray As Long
For rowFirstArray = 1 To UBound(firstArray,1)
    For rowSecondArray = 1 To UBound(secondArray,1)
        If firstArray(rowFirstArray, 3) = secondArray(rowSecondArray, 1) Then
            firstArray(rowFirstArray, 4) = secondArray(rowSecondArray, 2)

Is only needed if your two arrays are different sizes. Are they different sizes?


Hex-string representation of a byte array

Your code is good. The CXF code has a bug, and is missing leading-zero values when the byte value is less than 16.

Your code can be improved, though. It's doing a lot more work than it needs to do get the characters right.

Converting the value to a "longer" string and then taking the substring is a long-winded way of getting the padding right.

Consider a lookup-table for the task, and then use that as a mechanism for fast string building using a char array.

I have had a lot of success with this method:

private static final char[] hexchars = "0123456789abcdef".toCharArray();

private static String toHexRL(byte[] checksumArray) {
    int len = checksumArray.length * 2;
    char[] hchars = new char[len];
    int pos = 0;
    for (byte b : checksumArray) {
        hchars[pos++] = hexchars[(b>>4) & 0xf];
        hchars[pos++] = hexchars[b & 0xf];
    }
    return new String(hchars);
}

Note, I have put your method, my method, and the CXF method in to a test case here on Ideone: https://ideone.com/o66K1P

Note: To my knowledge, there's no authoritative (Java core library) for converting an array of byte to a hex string.


Style
You're not being charged by the character; there's no need to abbreviate "count", or "ret" (which I would call "score" instead).  Also, main has inconsistent brackets with the rest of the program.  Other than that, it looks good.

Globals
The globals are only being used by greed_rand, and would be better created within main and passed as parameters to greed_rand.

Counting Logic
Currently you're checking each possible quantity of '1's (and other numbers) separately, and not in order either, which makes it harder to ensure you're not missing a case and will fail if you change the number of total dice.  An improvement would be to check for the larger combinations first and just continue scoring as long as possible.  For example:

for(; count[1] >= 3; count[1] -= 3)
{
    score += 1000;
}
for(; count[1] > 0; --count[1])
{
    score += 100;
}

This also matches the score chart more clearly.

Output
You're outputting the end result of greed_rand, but not what list generated that result - which means you can't really tell if it was correct.  It would probably be better to replace greed_rand with a method that makes a random list, and pass that to greed yourself, so you can also output it:

std::vector<int> roll_dice(int count, std::mt19937 &engine)

Use of Templates (Optional)
While not required for this usage, greed would be a good candidate for taking a pair of generic iterators instead of requiring a std::vector:

template<typename Iterator>
int greed(Iterator begin, Iterator end)
{
   ...
   for (auto it = begin; it != end; ++it)
   {
       ++cnt[*it];
   }


I don't really understand how you want to use this so I'm just going to add a couple of comments for you to ponder.

Naming

It's more common to abbreviate Asynchronous to Async not Asynch when used in identifers: AsynchSimpleProducer<T> -> AsyncSimpleProducer<T>.

NewItem isn't a great name for an event, events generally need a verb to make sense e.g. Closed, Clicked, Closing are all good names for an event. Consider something like ItemAdded or similar.

Thread safety

You aren't raising your event safely:

if (NewItem != null)
    NewItem(item).Wait();

NewItem can change between the check and using it. If a listener unsubscribes in this time you'll get an Exception! The proper way to do this is:

var newItem = NewItem;
if (newItem != null)
{
    newItem(item).Wait();
}

Note that I have also added in braces as I personally think they should always be included, even for single line blocks.

Asynchronicity

I had to type something that made me very sad.

newItem(item).Wait();

It's not async if you immediately wait on it. It would be interesting to know what sort of work you're passing in here as it's not obvious whether you need to try to make this asynchronous or not. I'm concerned that you have confused threading and asynchronicity.

Edit

I can't believe I didn't mention this before, I must have been distracted...

If your event handlers throw (the things listening on the NewItem event), you're toast. Say you have 2 listeners, if the first one throws, the second wont be called.

You need to go through each one in the invocation list:

 // untested...
 var runningTasks = new List<Task>();
 foreach (var delegate in newItem.GetInvocationList())
 {
     runningTasks.Add(delegate(item));
 }
 // catch exceptions here.
 Task.WaitAll(runningTasks.ToArray());

I wish I could suggest something useful but I still haven't figure out what you intend on doing with this thing.


Review:

public void shuffleCards()

Should only shuffle cards, because that's what it says it does. Create new methods void playGame() int getFirstPick(), int getSecondPick(), boolean isAlreadyMatched(int card1, int card2), boolean areAllCardsMatched() and possibly others.

Assign these methods to the class that they should belong to.

Game
    void playGame()
    int getFirstPick()
    int getSecondPick()
    boolean verifyFirstPick(int firstPick)
    boolean verifySecondPick(int firstPick, int secondPick)

Cards
    void shuffleCards()
    boolean isAlreadyMatched(int card)
    boolean areAllCardsMatched()

Why?

Because right now you've got one long piece of code that does everything, and it's confusing you and causing bugs. By splitting it up, it'll be easier to identify what you need to do and whether the code is doing it.

If you do it right, you'll end up with code like this:

public void playGame(){
    //printInstructions(); //an idea, perhaps?
    setupGame();
    while(!isGameWon()){
        doTurn();
    }
    printGameWon();
}

That's awfully abstract, Pim.

Okay, lets dive a level deeper, in setupGame:

public void setupGame(){
    cards = new Cards();
    cards.shuffle();
    userInput = new Scanner(System.in);
}

That sets up the playing field and the input, it seems.

What's the next method? isGameWon()...

public boolean isGameWon(){
    return (cards != null && cards.areAllCardsMatched());
}

It's just a check for whether all the cards are matched. (There's a sneaky shortcut here; with cards != null I check whether the game has been initialized yet.)

Okay, what about doTurn() then? That one is a bit bigger.

public void doTurn(){
    int firstPick = -1;
    do {
        firstPick = getFirstPick();
    } while(!verifyFirstPick(firstPick));
    printFirstPick(firstPick);

    int secondPick = -1;
    do {
        secondPick = getSecondPick();
    } while(!verifySecondPick(firstPick, secondPick));
    printSecondPick(secondPick);

    checkMatch(firstPick, secondPick);
}

It handles getting the first picked card and the second picked card, then passes them along to checking for a match.

Let's go look at the checkMatch function.

public void checkMatch(int firstPick, int secondPick){
    if(cards.match(firstPick, secondPick)){
        printMatch();
        printRemainingMatches();
    } else {
        printNoMatch();
    }
}

We STILL haven't seen any real code doing anything. All I have shown you right now that actually does anything is the setupGame method. The rest just structures the game flow.

Function lists right now:

Game
    void setupGame();
    void playGame();
    void doTurn();
    void checkMatch(int firstPick, int secondPick);
    int getFirstPick();
    int getSecondPick();
    boolean verifyFirstPick(int firstPick);
    boolean verifySecondPick(int firstPick, int secondPick);
    boolean isGameWon();

    void printFirstPick(int firstPick);
    void printSecondPick(int secondPick);
    void printMatch();
    void printNoMatch();
    void printRemainingMatches();
    void printGameWon();

Cards
    void shuffleCards();
    boolean match(int card1, int card2);
    boolean isAlreadyMatched(int card);
    boolean areAllCardsMatched();

It'll be your task to implement the ones I haven't shown yet. You'll also have to move some of the variables so they're class members, not just declared in a function (hint: cards and userInput are two of these, I don't know if there are more).

Given the name of the functions, it should be easy to guess what they do.
shuffleCards shuffles the cards. match tests if two cards are a match. And so on...


Improve performance of Gaussian kernel function evaluation

I am never forget the day I first meet the great Lobachevsky.
In one word he told me secret of success in NumPy:
Vectorize!
Vectorize!
In every loop inspect your i's
Remember why the good Lord made your eyes!
So don't shade your eyes,
But vectorize, vectorize, vectorize—
Only be sure always to call it please 'refactoring'.

def kde_integration(m1, m2, sample_size=100, epsilon=0.000001):
    values = np.vstack((m1, m2))
    kernel = stats.gaussian_kde(values, bw_method=None)
    iso = kernel(values)
    sample = kernel.resample(size=sample_size * len(m1))
    insample = kernel(sample).reshape(sample_size, -1) < iso.reshape(1, -1)
    return np.maximum(insample.mean(axis=0), epsilon)

Update
I find that my kde_integration is about ten times as fast as yours with sample_size=100:
>>> m1, m2 = measure(100)
>>> from timeit import timeit
>>> timeit(lambda:kde_integration1(m1, m2), number=1) # yours
0.7005664870084729
>>> timeit(lambda:kde_integration2(m1, m2), number=1) # mine (above)
0.07272820601065177

But the advantage disappears with larger sample sizes:
>>> timeit(lambda:kde_integration1(m1, m2, sample_size=1024), number=1)
1.1872510590037564
>>> timeit(lambda:kde_integration2(m1, m2, sample_size=1024), number=1)
1.2788789629994426

What this suggests is that there is a "sweet spot" for sample_size * len(m1) (perhaps related to the computer's cache size) and so you'll get the best results by processing the samples in chunks of that length.
You don't say exactly how you're testing it, but different results are surely to be expected, since scipy.stats.gaussian_kde.resample "Randomly samples a dataset from the estimated pdf".