Overall, I'd say recursion is a good way to go. Good use of an IIFE to keep things tidy as well. I do however have some concerns.

Input checking

Firstly, if I pass an empty array, I get a stack overflow, since you only check for a length of 1 - not for a length < 1. I am technically passing the correct type (an array) to the function, so it should handle it (if I pass something that's not an array, then it's my own fault).

Also, if I pass [9] (or [31415]) I just get undefined back, though an empty array would probably be more fitting.

shift() is destructive

Be careful with shift()! You're modifying the array that's been passed to the function, even though it doesn't really "belong to you". The caller might still have a use for it.

For instance,

var numbers = [1, 2, 3];
var words = keypadPossibilities(numbers);
console.log("You typed " + numbers.length + " digits, producing " + words.length + " possible words");

will print

You typed 0 digits, producing 27 possible words

Wait, zero digits? Thing is, numbers is suddenly empty; everything's been shifted out by passing it to keypadPossibilities.

This of course also happens when the function recurses, which could spell trouble. Luckily, in your case, you don't use the input array for anything after having recursed, but if you did you'd find that the recursion had truncated it down to empty.

Don't use for...in for arrays

for...in will iterate properties of an object, and with no guaranteed order. It usually works for arrays, but it's not a sure thing. It's semantically different from iterating the actual, indexed elements in the array. So use either a regular ol' for loop, or - if you're targeting modern runtimes, maybe a forEach().

However, you could also use map() and reduce() in this case (see below).

Other stuff

This function-wrapper around a call to getPosibilities is unnecessary:

return function(pressed_keys)
{
    return getPosibilities(pressed_keys);
}

(Oh, and there's a typo: getPosibilities is missing an extra "s". I'll just use the corrected name from hereon out)

You could simply replace the above with just:

return getPossibilities;

and done.

However, with the point about shift() in mind, the easiest thing to do would probably be something like

return function(pressed_keys)
{
    return getPossibilities(pressed_keys.slice());
}

Now, pressed_keys gets sliced (duplicated) before it's passed to getPossibilities.

You could also do the slicing in getPossibilities (and do the direct return, shown above), but - as the code's already proved - you don't really need it there. But in the interest of being thorough, it'd look something like:

var currentIndex = keypad_mapping_indexes[0]
// ... snip ...
var charactersToGlueAtEnd = getPossibilities(digits.slice(1)); // duplicate array from index 1 and up

A few notes on style

In terms of style, I'm not a fan of brace-on-new-line in JavaScript. Yes, it works, but it can bite you, since JS will sometimes do automatic semicolon insertion at newlines and break your code. So the convention is to use brace-on-same-line style.

Also by convention, all names in JS should be camelCase. You're using a bit of both; aim for consistency.

Here's a possible version incorporating the points above

var keypadPossibilities = (function() {
  var keypadMapping = [
    null,
    ['a','b','c'],
    ['d','e','f'],
    ['g','h','i'],
    ['j','k','l'],
    ['m','n','o'],
    ['p','q','r','s'],
    ['t','u','v'],
    ['w','x','y','z']
  ];

  function getPossibilities(digits) {
    var characters = keypadMapping[digits.shift()],
        charactersToGlueAtEnd;

    if(!digits.length) {
      return characters || [];
    }

    charactersToGlueAtEnd = getPossibilities(digits);

    return characters.reduce(function (memo, character) {
      var words = charactersToGlueAtEnd.map(function (string) { return character + string; });
      return memo.concat(words);
    }, []);
  }

  return function (digits) {
    return getPossibilities(digits.slice()); // make sure we work on a copy of the input array
  };
})();


Is it a good idea to have a public inner class as a runner for a service?

I'm a bit confused by your code -- RecipeServiceImpl.buildInternalRunner has a return type of RecipeServiceImpl.Runner, and it's an Override?  Really?

Runner seems to be badly named, as it is easily confused with Runnable, which means something very different.  Is this really a RecipeServiceClient?

It's additionally confusing because you seem to be suggesting that RecipeService declares searchRecipes, but your runner doesn't implement that interface....

Given what you have shown thus far, I would have expected to see a single class, call it PiquetteRecipeService, that extends RecipeService but otherwise looks like the Runner you implemented.

class PiquetteRecipeService implements RecipeService {
    private final PiquetteClient piquetteClient;

    PiquetteRecipeService(PiquetteClient piquetteClient) {
        this.piquetteClient = piquetteClient;
    }

    public List<Recipe> searchRecipes(String query, int limit, int offset) {
        ...
    }

    // And so on....
}

This implementation does require that a PiquetteClient be created before the Service is created, but if the service can't do anything without the client, then that's the Right Thing[tm].

If that's not the right answer, then I think you haven't provided a clear description of the constraints you are trying to satisfy.

public interface RecipeService extends Serializable {
    RecipeServiceImpl.Runner buildInternalRunner(PiquetteClient piquetteClient);
}

OK, this is beyond broken.  You've got an interface, that declares a function which returns a type defined by a specific implementation of that interface.  Help, help, I'm being recursed!

BUT...

The good news is that you are clearly groping toward a Factory pattern.  If we change the spelling of a few things...

public interface RecipeServiceFactory {
    RecipeService createService(PiquetteClient piquetteClient);
}

In other words, instead of expecting Spring to create the service for you, you tell it to create an instance of the service factory for you, and then use that factory to create instances of the service when necessary.

public class DefaultRecipeServiceFactory {
    RecipeService createService(PiquetteClient piquetteClient) {
        return new PiquetteRecipeService(piquetteClient);
    }
}

Meanwhile, you would have a new interface declaration, using the old name...

public interface RecipeService {
    List<Recipe> searchRecipes(String query, int limit, int offet);
    Future<Integer> runRecipe(String recipeName, String asset);
    // ...
}

and the PiquetteRecipeService would implement this interface, delegating calls to the client.

Going back to your original question; with this design, yes it does it make sense to combine the service implementation and the factory that is coupled to it in a single class file.  I'd be more likely to nest the factory inside the service implementation, rather than the other way around:

public class PiquetteRecipeService implements RecipeService {
    public static class Factory implements RecipeServiceFactory {
        // ...
    }
}

If the service implementation isn't supposed to be public, then I would nest them the other direction (or keep them completely separate).

I still wouldn't quite be happy with this design, because arranging for the Factory to accept a PiquetteClient argument rather gives away the fact that the you are using Piquette under the covers.

Spring basically is a giant factory, so why do we need to roll our own?  If you were to let Spring create the PiquetteClient, for instance, then it could inject that client into the RecipeService it creates too.  If the problem there is that you need credentials, or a configuration or something to create the PiquetteClient, then maybe that's the argument that should be passed to the Factory.  Unclear -- just noting that as it stands, it is a bit odd.


Given some text and a word list, print the 7 most common correctly spelled words

List Comprehension

I'm not at all sure it'll run much faster (though it might--it's a little faster under Python 2.7, anyway), but I think a more Pythonesque approach would be to replace your loop:

    for word in list(words):
        if word in common_words or not word in correct_words:
            words.remove(word)

... with a list comprehension, something like:

words = [word for word in words if not word in common_words and word in correct_words]

Algorithm

To gain substantial speed, you probably want to rearrange your operations. Right now you're looking at each word in the input separately (and looking at all of them). Then, after you've found all the words that aren't common and are spelled correctly, you choose the 7 most common.

I'd reverse that: start by creating a Counter of all the input words. Then print those filtering words that are common or aren't spelled correctly. When you've printed seven of them, stop:

    words = [ word for line in readFile for word in line.split() ]

    c = Counter(words)

    counter = 0

    for word, count in c.most_common():
        if not word in common_words and word in correct_words:
           print word + ", "  + str(count)
           counter = counter + 1
           if counter == 7:
               break;

You could simplify that inner loop a little by by doing a little preprocessing. Instead of testing against both the common and correctly spelled lists, you could start by removing all the common words from the correctly spelled list, to get a single list of the words that are acceptable. Then when you're printing out your results, you'd check only against that one list. Given the sizes of the lists, this would be a win primarily if you did it once and saved the result so you can re-use it. If you re-did the preprocessing every time you ran the program, you'd probably use more time on the preprocessing than you'd save on the output loop.

There's probably more than can be done to make this neater as well, but nothing occurs to me immediately. At least for me in a quick test, this seems to run around ten to fifteen (or so) times as fast as the code in the question. The exact difference in speed will probably depend (heavily) on the size of input file though. In particular, I believe this is changing from \$O(N^2)\$ complexity to an expected complexity around \$O(N)\$1.

As an aside, I did consider (and test with) using a set instead of a list for common_words and correct_words, but at least in my testing, with the updated algorithm this didn't seem to make a difference that I could replicate dependably. With the original algorithm, however, changing these from list to set can improve performance considerably.

Logic

As it stands right now, your if/then chain:

if choice.strip() == "":
    choice = "alice-ch1.txt"
elif choice.endswith(".txt"):
    print(choice)
else:
    choice = choice + ".txt"
print(choice)

... prints out choice twice if it starts out ending with .txt. I suspect you really want something closer to:

if choice.strip() == "":
    choice = "alice-ch1.txt"
elif not choice.endswith(".txt")
    choice = choice + ".txt"
print(choice)

Magic number

It would probably be better to use something on the order of:

mostCommonLimit = 7

# ...

if counter == mostCommonLimit
    break;

If you want to get technical, it probably is still \$O(N^2)\$. The Counter presumably uses a hash table, which is \$O(1)\$ expected complexity, but can be \$O(N)\$ in the worst case (where all keys produce equivalent hashes). This is, however, so rare that in practice it's often ignored.


generating stochastic coloured noise for many oscillators

#include <math.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <iostream>
#include <random>

using namespace std;

Please don't put all the standard identifiers into the global namespace.  Use the C++ versions of the libraries, and qualified names.  If you really must drag some identifiers in (as is often required for argument-dependent lookup), be specific and keep their scope small.
And try not to mix C standard I/O and C++ streams if possible.
#include <cmath>
#include <cstddef>
#include <cstdlib>
#include <iostream>
#include <random>


Summing all parameters, except the last, which should be subtracted instead

Using an iterator is commonly considered more Pythonic than indexing, and avoiding an if makes code more beautiful in any language:

def f(*args):
    r = reversed(args)
    return -next(r, 0) + sum(r)


Get all objects which contains any given array of Enums

There is nothing particularly wrong with your current code, although I have a couple of comments:

The name interactions1 of the local variable is slightly confusing.
Instead of having a break, you could have a separate method that determines if a given Interactable contains as interactions one of the given interactions.

With the Stream API, you could have the following:

public List<Interactable> getObjectsByInteractions(final Interactions[] interactions) {
    return objects.stream()
                  .filter(object -> Arrays.stream(interactions).anyMatch(object.getInteractions()::contains))
                  .collect(Collectors.toList());
}

This creates a Stream<Interactable> of your objects. It then filters out all the unwanted object: for that a Stream<Interactions> of the given interactions is created and anyMatch tells whether object.getInteractions() contains one of those interactions. Finally, the elements are collected into a list.


jQuery and cross browser input fields focus handling

I'm not quite sure if this will do quite what you want, but here is my rehashing of the code:

$(document).ready(function() {
    $('table[id^="block"] input, select').bind("focus blur", function() {
        var $this = $(this);
        $this.closest("td").prev().toggleClass('highlightLabel');
        $this.not("select").toggleClass('highlightField');
    });
});

You can see it in action here on jsFiddle.

As far as I can tell, the only thing I changed, behavior-wise, is that the select dropdown list does not have a background color when focused. IMO, it looks better that way, but you might prefer it with the background color.

It seems to work the same on all the browsers I tested, but let me know if it doesn't and I'll look at it and see if I can fix it.


None of your columns are marked non-nullable. This is important for data integrity.
duration and date both seem mis-represented as int. You're in PostgreSQL, so read https://www.postgresql.org/docs/current/datatype-datetime.html and then consider instead

interval for duration, and
date for date


Fetch and print all properties of an object graph as string

You should have a guard clause against someone passing in null

PropertyInfo has a PropertyType and you should use that instead of

 Type valueType = value.GetType();

as if value is null you will get a null reference error where PropertyType will give you the type of the property.

You will need to fix this line as well if value is null.  Again you will get a null reference error

 result += value.PropertiesToString(++tabs);

Better to compare types then their names.  Instead of

 valueType.Name.Equals("String")

use

 valueType == typeof(string)

You should separate out gathering the properties and displaying them.  I would have an extension method that returned IEnumerable> and then you could use linq to convert that into the strings and how you want it displayed.

Other things to consider is if you have two object that reference each other you will get a stack overflow.

I would recommend looking at https://docs.microsoft.com/en-us/dotnet/api/system.runtime.serialization.objectmanager?view=netframework-4.8 to see an example of an object walker.  I think making the class IEnumerable is a bit confusion when learning and they would have been better making a method that returns IEnumerable.  still a good place to start when learning about walking an object graph.


First, to answer your questions about new/delete: Everything you new, you must delete at some point, or you leak memory. When you new, you are given a pointer to the object that has been allocated. Similarly, when you use delete, you must use a pointer to that same object, and the memory that was allocated will be freed. After doing this, the pointer will be pointing at freed memory and you should not delete this again. It doesn't matter where you use new, in main() or otherwise, you need to delete it at some point.

Now to your code: Your code will double-delete either the first node when the list size is 1, or the last node, when the list size is greater than 1. Double deletes cause undefined behaviour including crashes.

Let's look at list of size 1 first. Your while loop won't be entered, and you basically skip down to the end where you do

delete this->startNode;
delete this->endNode;

Since startNode and endNode should both be pointing to the only node in the list, it will get deleted twice!

If you have a list of more items, the loop will delete every item except the first. Then the last two statements occur. In this case, this->endNode will be the original end of the list (since you never alter it here) and so it will be deleted twice.

Here is a simpler version that just deletes every node, starting from the first.

~List
{
    ListNode* current = startNode;
    ListNode* next;

    while (current != NULL) {
        next = current->next;
        delete current;
        current = next;
    }
}


SSL Mutual Authentication, with one specific Root Certificate

The X509 certificate contains by itself a system to specify and verify chain and root certificates, by doing this you are actually creating a certificate without a proper root certificate but implementing a root certificate by yourself.
Looks like a waste of time just for the pleasure of doing something less secure...


Parse date format in Pandas using Python

This post on Stack Overflow explains why you are getting the wrong years.

https://stackoverflow.com/questions/37766353/pandas-to-datetime-parsing-wrong-year

Based on your code all of the two digit years in your data set will be converted to 19XX years. The only problem I can see is that if your data set includes dates across both centuries ( 19XX and 20XX) you'll end up forcing anything that should be 20XX to be 19XX the way you have it written. If your data set has dates in both centuries I'd recommend preprocessing your date strings to make them unambiguous (change 16MAR39 to 16MAR1939). This will require additional information from another tag in your data set if you've got it.

To your specific questions:

Since the data is ambiguous there isn't a way to get it right the
first time.  If you preprocess the data then it should work as you
want with the single pd.to_datetime command.
Processing the data on the front end to resolve the ambiguity (based on other information in your set) is probably a better solution than assuming you need to offset every date after 2000. For example, 1MAR05 will be read as 2005, then your code will offset by 100 years and you'll get 1905 when maybe it should have actually been 2005.

Amateur coder here learning too, but I don't think there is a built in function to make your data unambiguous or force a specific century prefix.


efficiency

Overall, the code looks idiomatic and sensible, no major issues. But you want to tweak it for efficiency. Here are some things you might try.

Most importantly, instrument elapsed time, so you can tell if a tweak is useful:

    t0 = time.time()
    ...
    elapsed = time.time() - t0

And definitely use the profiler, so you know where to focus your efforts.

Ok, with that in hand, it looks like you need to synthesize some boolean columns. There are several columns that you repeatedly inspect, e.g. Transaction Description. Perhaps you could add them to the spreadsheet, to avoid repeatedly processing unchanging data? Another approach would be to build up a list of rows and then do data = pd.DataFrame(rows). This would let you examine each Transaction Description once and derive a couple of columns. But frankly, I'm skeptical this would improve your timings at all, the code looks fine as is.

style

Do use a pep8 linter: flake8, and follow its advice.

In hard-to-read identifiers like spinscrap, introduce an underscore so it is clear to the Gentle Reader where word breaks are.


First of all "F:\test\Test.csv" should be escaped or a verbatim string:

new StreamWriter("F:\\test\\Test.csv")

Or:

new StreamWriter(@"F:\test\Test.csv")

Also you should not hardcode paths in your code but I suppose this is only because of posting here (but you'd better show your actual code cleaned from sensitive information).

StreamWriter defaults to UTF-8 encoding. It may be what you need but I usually like to make it explicit to anyone reading my code:

new StreamWriter(path, false, Encoding.UTF8)

In my opinion main issue here is that this function is doing too many things: loading required data, writing to output and logging to console.

If output file size is not too big you may start with this (type names are fictional and some functions need a better name, I don't have enough context to pick a proper one).

Let's first define a class for your server data, it's also responsible for loading from context. If your scenario will become more complex you may want to introduce a separate Loader class and keep Server as a POCO object.

Note: I don't know about SharePoint ListItem object (see also BCdotWEB's answer), if you already have everything you need in ListItem then you may drop Server object.

sealed class Server
{
    public Server(Context context, ListItem item)
    {
        context.Load(server);
        context.ExecuteQuery();

        Name = Convert.ToString(item["Server"]);
        Service = Convert.ToString(item["Service"]);
    }

    public string Name
    {
        get;
        private set;
    }

    public string Service
    {
        get;
        private set;
    }

    public override string ToString()
    {
        return $"{Name}, {Service}";
    }
}

Now you can simplify your function moving different responsibilities to different functions. Your public function has to implement current behavior but must be easy to extend/change (for example if logging isn't for console, if output file is not specified by its path and so on):

public static void WriteServersToShutDown(string path, Context context,
    IEnumerable<ListItem> serversToShutdown)
{
    if (context == null)
        throw new ArgumentNullException("context");

    var content = ConvertToString(LoadData(context, serversToShutdown));

    Log(content);
    WriteFile(path, content);
}

To load data is the basic reusable block of your code (for example if you also need to perform some action, not just to dump a log):

private static IEnumerable<Server> LoadData(Context context,
    IEnumerable<ListItem> serversToShutdown)
{
    return serversToShutdown.Select(x => new Server(context, x));
}

You also need a function to convert IEnumerable<Server> list into a string with one line for each entry. This is the function you will edit if output format will be changed. In this example I rely on Server.ToString() implementation but it's often a bad idea, for this kind of tasks I usually override ToString() for debugging/logging purposes and I move formatting responsibility to a separate IFormatProvider object.

private string ConvertToString(IEnumerable<Server> servers)
{
    return String.Join(Environment.NewLine, servers);
}

Few helper functions:

private static void Log(string text)
{
    Console.WriteLine(text);
}

private static void WriteFile(string path, string content)
{
    File.WriteAllText(path, content, Encoding.UTF8);
}

Everything may be rewritten as:

var content = String.Join(Environment.NewLine,
    serversToShutdown.Select(x => new Server(context, x)));

Console.WriteLine(content);
File.WriteAllText(path, content, Encoding.UTF8);

Then why so many functions? Because each function performs exactly one task and if you need to change anything you will need to change only one function. This may not be obvious in this simple example but it's important for bigger programs. Also note that smaller functions may be reused and you keep all the code in sync:

foreach (var server in LoadData(context, serversToShutdown))
    ForceShutdown(server);

If you need to introduce a factory class (above mentioned loader) you need to change only LoadData() function. Do you need to change output file encoding or to add some error handling? Just go to WriteFile() and all callers will be updated. You change log to something else instead of console? Pick Log() function. Above everything else there is readability: to understand what WriteServersToShutDown() does you need to inspect just three lines of self-explicative code (after you renamed those functions with proper names from your domain).


Check field values against a preset object

Inside one of the $.each calls, you could simplify this part:

if (flag == false){
    return false;
}

to this:

return flag;

When the value is true, $.each will continue normally, and stop after it is false, so the behavior remains the same.

Instead of:

if (flag == false) {

It's more common to write:

if (! flag) {

For simplicity, it might be a good idea to flip the condition:

if (flag) {
    $(preset + ' i#id').attr('class', 'radio-checked on');
} else {
    $(preset + ' i#id').attr('class', 'radio-unchecked');
    return false;
}

And to reduce code duplication, I would extract the dom lookup that is common in both branches of the if-else:

var preset = $(preset + ' i#id');
if (flag) {
    preset.attr('class', 'radio-checked on');
} else {
    preset.attr('class', 'radio-unchecked');
    return false;
}

The two innermost loops use $.each,
but the outer loop is a traditional for.
For the sake of consistency, it might be good to use $.each for all.


Process POSTed data and add default string if missing

Addressing two issues here:
Setting a default value
PHP now has a null coalesce operator (??).
This allows you to easily set a default value if the variable is null.
$exampleArray = $_POST['lala'] ?? [];

(Here, I am setting the default value to an empty array)
Refactoring code
Any time you catch yourself copy/pasting a chunk of code, that’s a signal to start refactoring.  So the code you provided had almost everything in the if and else block repeated.  Just pull the repeated stuff out. In this case, you don’t even need the else.

if(isset($_POST['submit'])) {
    //for update
    $site_id['locale'] = 'tr';

    //new
    $exampleArray = $_POST['lala']) ?? [];

    $example = null;
    if(($key = array_search($site_id['locale'], $exampleArray, true)) !== false) {
        unset($exampleArray[$key]);
    }

    $FirstString = array($site_id['locale']);
    $exampleArray = array_diff($exampleArray, $FirstString);
    usort($exampleArray);
    $exampleArray = array_merge($FirstString, $exampleArray);
    //print_r($exampleArray);
    $myArray = array();
    foreach ( $exampleArray as $key => $value ) {
        $myArray[] = $value;
    }
    echo implode( ', ', $myArray );

    // Note, should always redirect after a post.
    // Post means change data, so after you have
    // stored the changes, redirect to the next (or
    // back to same) page. Cannot be any output
    // before this (print, echo, blank lines, html)

}
```


Count number of isosceles triangles in a set of points

Try another algorithm

Instead of considering triangles, you could simply consider lines starting from a point.

For each point, compute the distance between this point and every other point; you will get a number of distances.

Now, for every distance from a point, count the number \$n\$ of equal distances, and add \$n*(n-1)/2\$ to the number of isoceles triangles. If you use an std::unordered_map<unsigned long long, unsigned> to count the number of occurrences of every distance from a point, it should give you a \$O(n^2)\$ algorithm, if I'm not mistaken.

Note: this method might count the same triangle several times if a triangle happens to be equilateral. Unfortunately, I don't see a simple way to circumvent this problem.

C++ pedantry

I talked about the math first since it's what really matters, but honestly, your C++ isn't the prettiest C++ around, so here we go for the C++ review:

Please don't use typedef unsigned long long llu;. Even if it's long to write, llu doesn't convey any meaning to anyone reading it. Type the full name and people will know out-of-the-box what type they are using.
distance_p looks like it computes the distance between p1 and p2, but it actually computes the the squared distance between them. Make that clear by naming the function squared_distance.
Also, distance_p does not alter its parameter. Therefore, pass const references instead of simple ones:

inline unsigned long long squared_distance(const point_t &p1, const point_t &p2)
{
    return (p2.x - p1.x)*(p2.x - p1.x) + (p2.y - p1.y)*(p2.y - p1.y);
}

You don't need to use typedef like it is done in C to write point_t instead of struct point_t. In C++, an equivalent typedef is done automagically by the compiler. Simply declare your struct like this:

struct point_t {
    unsigned long long x, y;
};

When using components from the standard library, try to always prefix them with std::, even in they come from the C standard library (std::printf, std::scanf, etc...). Prefixing them may help to avoid name clashes and make it easier to search for standard library components in your code.
Try not to put everything in main. Here, you can easily put the algorithm which looks for isoceles triangles in its own function and let main handle only the input & output operations. Splitting code into small logical bricks instead of tightly coupled ones is known as separation of concerns.

Putting it all together

Since there are many things to take into account. I decided that I could as well show you how I would have implemented count_isoceles_triangles as described using C++11 (that's not exactly how I would have done it, but it's closer to it than what you currently have):

struct point_t
{
    unsigned long long x;
    unsigned long long y;
};

unsigned long long squared_distance(const point_t &p1, const point_t &p2)
{
    unsigned long long a = p2.x - p1.x;
    unsigned long long b = p2.y - p1.y;
    return a*a + b*b;
}

template<std::size_t N>
unsigned count_isoceles_triangles(const std::array<point_t, N> points)
{
    unsigned nb_triangles = 0;

    for (const point_t& p1: points)
    {
        std::unordered_map<unsigned long long, unsigned> distances;
        for (const point_t& p2: points)
        {
            unsigned long long dist = squared_distance(p1, p2);
            distances[dist] += 1;
        }

        for (auto&& dist: distances)
        {
            unsigned count = dist.second;
            nb_triangles += count * (count - 1) / 2;
        }
    }

    return nb_triangles;
}

Note that there are still some additional differences: I used std::array since it's not easy to pass a C array to a function correctly. Also, I didn't check whether p1 == p2 before counting the distances, but it's also something that should be done.


Here's my take on it:

def getFirstParagraph(txt: String): String = txt.lines.next

As to the null objection: in idiomatic Scala, you don't use null. If there's some API which might return you a null string, then, at that point, you turn it into an Option, and handle the Option elsewhere as needed.

Handling null (or even Option) at the getFirstParagraph method is misplaced.


First of all, the models need to be defined, conforming to the Decodable protocol. Starting with the base class and then the subclass, see the example below:

class FieldDefinition : NSObject, Codable {
    let type: String

    enum CodingKeys: String, CodingKey {
        case type
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.type = try container.decode(String.self, forKey: .type)
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(self.type, forKey: .type)
    }
}

class TextFieldDefinition: FieldDefinition {
    let maxLength: Int

    enum TextCodingKeys: String, CodingKey {
        case maxLength
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: TextCodingKeys.self)
        self.maxLength = try container.decode(Int.self, forKey: .maxLength)
        try super.init(from: decoder)
    }

    override func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: TextCodingKeys.self)
        try container.encode(self.maxLength, forKey: .maxLength)
        try super.encode(to: encoder)
    }
}

And here comes the tricky part. Next we create an enum DemoClassKeys, which is used to decode the dictionary containing the array of fields.

We also define an enum FieldDefinitionTypeKey which is used to serialize the type field (wrapperType in your case) for each object in the array.
And a final enum FieldDefinitionTypes with specifies all the possible FieldDefinition types.

With all the enums specified we can get to the serialization :

class DemoClass: Decodable {
    var fieldDefinitions: [FieldDefinition]

    enum DemoClassKeys: String, CodingKey {
        case fieldDefinitions
    }

    enum FieldDefinitionTypeKey: CodingKey {
        case type
    }

    enum FieldDefinitionTypes: String, Decodable {
        case textFieldDefinition = "TextFieldDefinition"
        case deterministicFieldDefinition = "DeterministicFieldDefinition"
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: DemoClassKeys.self)
        var arrayOfFieldType = try container.nestedUnkeyedContainer(forKey: DemoClassKeys.fieldDefinitions)
        var fieldDefinitions = [FieldDefinition]()

        var tmp = arrayOfFieldType
        while(!arrayOfFieldType.isAtEnd) {
            let fieldDefinition = try arrayOfFieldType.nestedContainer(keyedBy: FieldDefinitionTypeKey.self)
            let type = try fieldDefinition.decode(FieldDefinitionTypes.self, forKey: FieldDefinitionTypeKey.type)
            switch type {
            case .textFieldDefinition:
                fieldDefinitions.append(try tmp.decode(TextFieldDefinition.self))
            case .deterministicFieldDefinition:
                fieldDefinitions.append(try tmp.decode(DeterministicFieldDefinition.self))
            }
        }
        self.fieldDefinitions = fieldDefinitions
    }
}

And Here is the full working Demo:

var json = """
{
    "fieldDefinitions": [
        {
            "type": "TextFieldDefinition",
            "maxLength": 5
        },
        {
            "type": "DeterministicFieldDefinition",
            "defaultValue": "VISA"
        }
    ]
}
"""

let jsonDecoder = JSONDecoder()
do {
    let results = try jsonDecoder.decode(DemoClass.self, from: json.data(using: .utf8)!)
    for result in results.fieldDefinitions {
        print(result.self)
    }
} catch {
    print("caught: \(error)")
}


There is a more concise possible approach if you, first, convert the test sequence into the corresponding positions in the base sequence, then, substract each position to the next one (replace "ge 0" with "gt 0" if duplicates are not allowed):

declare function local:testOrder2($baseSequence, $testSequence) {
    let $positions := $testSequence ! index-of($baseSequence, .)
    return min(for $pos at $index in tail($positions) return $pos - $positions[$index]) ge 0
};

Your recursive approach will stop at the first disorder detection so, depending on inputs, it might be faster!


Spaces come after commas

-    let v = vec![true,false,true];
+    let v = vec![true, false, true];

Define the closure inline in the fold call. This allows removing the explicit types
Cloning the accumulator is more expensive than it needs to be. You have been given ownership of the vector, just declare it mutable and push to it.

The code now looks like:

let result = v.iter().enumerate().fold(vec![], |mut acc, p| {
    if *p.1 {
        acc.push(p.0);
        acc
    } else {
        acc
    }
});

Extract out the common part of the closure that returns the acc
Destructure p to give the components names.

The code now looks like:

let result = v.iter().enumerate().fold(vec![], |mut acc, (index, value)| {
    if *value {
        acc.push(index);
    }
    acc
});

I advocate to basically memorize all the methods on Iterator. In this case, filter, map, and collect allow writing the entire thing more succinctly, equally efficiently, as well as more flexibly.
There's no need to allocate the Vec, an array / slice works the same.

The code now looks like:

fn main() {
    let v = [true, false, true];

    let result: Vec<_> = v.iter()
        .enumerate()
        .filter(|&(_, &value)| value)
        .map(|(index, _)| index)
        .collect();

    println!("{:?}", result);
}

  I would expect that filter() filters out non true values, so indices would shift, but it seems like it's not happening

Yes, filter does remove the non-true values. The important thing to recognize is where the indices are added.

With iter().enumerate().filter(), enumeration happens before the filtering. Each index is added based on an unfiltered iterator.

If the code had instead been iter().filter().enumerate(), the enumeration happening after the filtering, then the index would have been added based on the filtered iterator. This would result in the indices 0, 1, 2, ..., which isn't very useful, as you point out.


Angular Rest API generic service and implementation service

I think you can use HTTP Interceptors to simplify the code.

For the authorization

@Injectable()
export class AuthorizationInterceptor implements HttpInterceptor {

  constructor() {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    // skip requests for local assets
    if (request.url.indexOf("assets/") >= 0) {
      return next.handle(request);
    }

    const apiReq = request.clone({
      url: request.url,
      headers: request.headers.set('Authorization', `Bearer ${localStorage.getItem('access_token')}`)
    });
    return next.handle(apiReq);
  }
}

For the base url

Something along the line

@Injectable()
export class BaseUrlInterceptor implements HttpInterceptor {

  constructor(
    @Inject("BASE_API_URL") private baseUrl: string) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    // skip requests for local assets
    // maybe put extra condition to allow for multiple API usage
    if (request.url.indexOf("assets/") >= 0) {
      return next.handle(request);
    }

    const apiReq = request.clone({
      url: `${this.baseUrl}${request.url}`
    });
    return next.handle(apiReq);
  }
}

Of course, the module should define the interceptors:

  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthorizationInterceptor,
      multi: true
    }
  ]


The case determination code (src[i] <= 'Z' && src[i] >= 'A') doesn't look right (think about locales). isupper and islower are specifically designed to deal with that. Besides, you are already using toupper and tolower.


Selecting product variants that satisfy all option criteria

I'm not quite sure I understood your requirements, but as I understand it you want to find the variant id for a set of values with the values 1, 4, 7 for the three options.
In other words, you need to do a double join in order to access the three different values, this can be achieved using some thing like this:
SELECT t1.variant_id, t1.value_id t1v, t2.value_id t2v, t3.value_id t3v
  FROM product_variant_values as t1
       JOIN product_variant_values AS t2
         ON t1.variant_id = t2.variant_id AND t2.option_id = 2 AND t1.option_id = 1
       JOIN product_variant_values AS t3
         ON t1.variant_id = t3.variant_id and t3.option_id = 3

When running this query as is, using a temporary table built from variant_id's up to 7 from http://prntscr.com/99sxp8, I got the following output:
variant_id t1v t2v t3v
1           1   4   7
2           1   4   8
3           1   4   9
4           1   5   7
5           1   5   8
6           1   5   9
7           1   6   7

Notice in this output how I've connected the t1 table to option_id=1, and t2 to option_id=2, and so on. Therefore when adding this line:
 WHERE t1.value_id = 1 AND t2.value_id = 4 AND t3.value_id = 7

One can limit the query to a given value set:
variant_id t1v t2v t3v
1           1   4   7

In other words, variant_id = 1 is the only one having the combinations of values 1, 4, 7.
Update: Generalisation to multiple options
The method above could be extended to any number of options, but the cost of it expands for each option you add.
Another option for solving this kind of problem on this end, is to make n different selects, and then doing a intersection of matching variant_id's. If your final intersection has only one element, you've found your variant_id, and if no or more than one element you need to handle that accordingly.
Addendum: Ultimate solution
The solution above was what I came up with when focusing on the join part of your question, and your request to remove the second query. When thinking a little more on it, it's the first query you want to remove. Try this one on for size:
SELECT count(*), variant_id FROM product_variant_values
 WHERE (option_id = 1 AND value_id = 1)
    OR (option_id = 2 AND value_id = 4)
    OR (option_id = 3 AND value_id = 7)
GROUP BY variant_id
HAVING COUNT(variant_id) = 3

If you get more than one or none resulting row out of this query, you have a problem. This is also easily extensible, as you just need to change the matching option count on the HAVING COUNT section and add appropriate extra groups on the OR parts.


In terms of security, you should be safe from SQL injection since you are using parameterized queries as recommended.  That's true whether or not you validate the names using the regex.  Do not perform any additional escaping — that would only mangle your data.

That regex is for enforcing your business rules (i.e. you want to reject names written in Cyrillic, names with French accents like é, Irish surnames like O'Something), and has nothing to do with database security.

I do not recommend mixing PDO with the WordPress database API.

The WordPress documentation recommends that you use $wpdb->insert() for simple INSERT queries.

In accordance with the WordPress documentation, you should check the return value from $wpdb->query() — a FALSE value indicates failure.  You should do that before declaring victory with echo json_encode(['status' => true]);.

if (!empty($errors)) {
    echo json_encode(['status' => false, 'errors' => $errors]);
} elsif (FALSE === $wpdb->insert('people', ['name' => $_POST['name']], '%s')) {
    echo json_encode(['status' => false, 'errors' => ['Database error: ' . $wpdb->last_error]]);
} else {
    echo json_encode(['status' => true]);
}


IMHO your code is fine. The "problem" with XSLT variables is that they are NOT variables but more resemble constants: once set they cannot be changed anymore. Also, their scope is restricted to anything that follows their definition until the closing tag. In particular they are NOT visible in any ancestor tag. The combination of both results in the type of constructs that you have used above.

What is most disturbing is the fact that you usually have to repeat the testing of the criterion again and again if several variables depend on the same criterion. Again there's nothing generic that you can do about this, but of course, you can always at least create another variable holding the result of the test and then use that several times.

Depending on the context of your XSLT I would suggest two alternatives which may or may not be more elegant:

a) works in XSLT 1.0 and 2.0: If you just define the variables to be used as parameters to a template-call consider writing the template-call twice once in the when as once in the otherwise portion. This way you will end up with just one <choose>.

b) Works only well in XSLT 2.0 (or a little awkward in XSLT with node-set extensions): move the check of the criterion and the selection of the definition values into a template and return the "set" of values to the assigned in a node-set. In a way you can regard this node-set as a record whose attributes have been set according to the criterion. See example below.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
    version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" />

  <xsl:template name="get_values">
    <xsl:param name="catalog"/>

      <xsl:choose>

        <xsl:when test="count($catalog/lookup) &gt; 0">
          <PRODUCT VALUE="{$catalog/lookup/Product}"/>
          <AREA VALUE="{$catalog/lookup/Area}"/>
        </xsl:when>

        <xsl:otherwise>
          <PRODUCT VALUE="UNK"/>
          <AREA VALUE="UNK"/>
        </xsl:otherwise>

      </xsl:choose>

  </xsl:template>

  <xsl:template match="/">

    <xsl:variable name="Catalog" select="."/>

    <xsl:variable name="my_config">
      <xsl:call-template name="get_values">
        <xsl:with-param name="catalog" select="$Catalog"/>
      </xsl:call-template>
    </xsl:variable>

    <xsl:message>
      The value of PRODUCT is <xsl:value-of select="$my_config/PRODUCT/@VALUE"/>
      and the value of AREA is <xsl:value-of select="$my_config/AREA/@VALUE"/>
    </xsl:message>

  </xsl:template>

</xsl:stylesheet>

This solution is definitely not shorter than yours but it resembles more other standard programming languages. The record type approach may come in especially handy if you have a lot of templates requiring the attributes in the record.


Recording timeback seconds of video based on compared pixels from an image

import PIL.ImageGrab
import PIL.Image
import time
from collections import deque
import threading
from numpy import *

Generally, import * is frowned upon because it makes it hard to figure out where things come frome

def get_pixel_colour(i_x, i_y):
    return PIL.ImageGrab.grab().load()[i_x, i_y]

You don't appear to actually use this function

class framebuffer:

Python style guide recommends CamelCase for class names

    def __init__(self,size):
        self.buffer = deque(maxlen=size)
        self.i= 0

i is kinda hard to guess what its for.

    def add_frame(self, frame):
        self.buffer.append(frame)
    def remove_frame(self):
        return self.buffer.popleft()

You don't ever use this method

    def write_frame(self):
        x = self.buffer.popleft()
        self.i+=1
        x.save("tm\screengrab"+ str(self.i).zfill(10) +".jpg")
        print "tm\screengrab"+ str(self.i).zfill(10) +".jpg written, ", len(self.buffer), "to go "
    def is_empfty(self):

Misspelled name and never used

        return (len(self.buffer)>0)

You don't need the parens around the whole expression

class mythread(threading.Thread):
    def run (self):
        while(True):

No need for those parens. Let your tokens breath

            if (len(self.frameb.buffer) > 0):

Its odd that you define a is_empfty function but don't call it.

                self.frameb.write_frame()
            else:
                time.sleep(1)

Python has a Queue.Queue class which implements a thread-safe queue. That'll be a better idea then a list because its guaranteed to be thread safe. Also, if you try to pop from an empty queue it will wait until an item is pushed onto the queue. That way you don't need to do the time.sleep() and loop thing here

    def setbuffer(self,frameb):

The python style guide recommends names like set_buffer

            self.frameb = frameb

I'd also implement something like this by passing the frame buffer to the constructor. I'd also probably combine these two classes. They are tightly coupled anyways.

seedimage = PIL.Image.open("seed.bmp")
pos_x = 983
pos_y = 263

Instead, how about storing the position as a tuple? You can pass a tuple to index the arrays

recpixel = seedimage.load()[pos_x, pos_y]
print "The pixel is now", recpixel
fps = 50
skipticks = 1/(fps*1.0)
i= 0

Any sort of complex logic like this should really be in a function. It'll be somewhat faster that way.

timeback = fps * 3
allframes=framebuffer(timeback)
nextsnap=time.clock()
recordframes = framebuffer(None)
t= mythread()
t.setbuffer(recordframes)

print 'Starting thread'
t.setDaemon(True)
t.start()

I'd do at least the setDaemon instead the thread. (And are you sure you want a Deamon thread?)

print 'starting program'
print skipticks, fps
while (True):
    tim= time.clock()
    i=i+1

use for i in itertools.count(): instead the while loop, and you want have to manually track the i

    x = PIL.ImageGrab.grab()
    allframes.add_frame(x)

avoid names like x. Makes it hard to follow your code

    imp_pixel = x.load()[pos_x, pos_y]
    r, i = array(recpixel),array(imp_pixel)

This override your previous i, suggesting it wasn't really important enough to keep track of anyways

    if (sum(r-i)<1 and sum(r-i)>-1 ):

python has a syntax -1 < sum(r-1) < 1 which is nicer for these sorts of things

        print "recognized", sum(r-i),"with size:", len(allframes.buffer)
        recordframes.buffer.extend(allframes.buffer)

Why don't you make allframes a list? It doesn't use any of the other behavior of the class you made.

        allframes.buffer.clear()
        sleep(10)

I don't know why you are sleeping here

    # this is the sleep that limits the fps
    nextsnap+=skipticks
    sleeptime = nextsnap-time.clock()
    if (sleeptime>0):
        time.sleep (sleeptime)

Note that time.sleep isn't very accurate as timing goes.


Use EXPLAIN in the sql console to determine what the query optimizer is doing with each query.  This will give you clues as to how each query performs, and may also help you optimize further, for example by indicating places where adding an index will speed the query up.
Run each of the queries in a loop and benchmark how long they take! If you're using PHP just wrap the query execution in a for loop and execute it 100 times or so.  Record the microtime() before you start and do it again at the end.  Subtract the start time from the end time and you'll have your benchmark.


Invert rows and columns in an Excel file

Another way to solve this, without using openpyxl and thereby slightly defeating the purpose of learning more about that, would be to use pandas, where this is quite short:

import pandas as pd

# This would load the first sheet by default, but we need the name to save it again
# df = pd.read_excel(filename)

sheets = pd.read_excel(file_name, sheet_name=None)  # all sheets
sheet_name, df = next(iter(sheets.items()))         # first sheet
df = df.T                                           # transpose
df.to_excel(file_name, sheet_name)                  # write back

This uses pandas.read_excel to read the file and pandas.DataFrame.to_excel to write it back. You need to have the xlrd module installed for this to work.

Feel free to wrap it in functions again if needed.

This should be faster than the manual iteration in Python, since the transpose should happen at C speed.


For a coding contest, the answer is almost never to implement the problem the same way as it is given.
For example here, functions A and B are actually intentionally misleading. Function A is also known as Euler's Totient, and function B computes the sum of totients of divisors which is the same as the original number. Detailed review of them is therefore a waste, functions A and B don't need to be implemented at all.
Function C can be improved by noting that the lowest divisor of a number is necessarily a prime, so calling check_prime is unnecessary. If itr was a * b then a and b would have been found first and divided out of remNum already, making itr not a divisor of remNum.
The square root is also unnecessary, and relatively expensive. It can be avoided by testing itr * itr <= numb instead. There is no risk of overflow given that numb <= 1000000. Further refinements are possible.
Function D can be improved by caching the partial sums. In isolation that would not help, but there can be multiple test cases during a run of the program, and they can reuse the previously computed sums. For example as an extreme case, after the test case 1000000 has been used, any further test cases could be essentially free, because all possible cases would have been calculated at that point. Also, after funcD(10) has been evaluated, funcD(20) could start with that result instead of starting over from scratch.


Finding the number of occurrences of a string in another string

I don't like nested loops.  They are generally unnecessry
and are often confusing. So instead of your two loops, I would extrac the
inner loop to a function, for example:

int key_search(const std::string& s, const std::string& key)
{
    int count = 0;
    size_t pos=0;
    while ((pos = s.find(key, pos)) != std::string::npos) {
        ++count;
        ++pos;
    }
    return count;
}

This searches the inputs string s for occurances of string key and returns
the number of matches.  A few things are worth noting:

The parameters are passed as const references - const because you don't change them and references for efficiency.
I used string::npos as the idicator of failure from strings find
method, instead of -1 (-1 would give a warning from the compiler if you have
sign conversion warnings enabled).
I didn't use a while(true) loop but instead used the return from s.find
directly to control the loop.
I pre-incremented variables instead of post-increment (++pos, not pos++)
which can be more efficient (although with built in types it makes no
difference).
pos (your start) is of type size_t, not int. Or you could use std::string::size_type, which is the also size_t.
It is normal to prefix your use of standard library things with std::, so
string becomes std::string etc.

The main loop now just needs to call key_search

int i = 0;
for (auto it = keys.begin(); it != keys.end(); ++it){
    frequency[i] = key_search(s, *it);
    ++i;
}

With C++11 you can use auto to simplify the iterator definition.  You don't
show what frequency is, but I'm assuming it is an array (which are generally
best avoided in C++).


Calculate future date based on business days (using Objects)

First of all, you can get away from having to deal with weekends altogether by using:

$to->modify('+1 weekday');

I think using the above and due to the nature of your function just needing to count X number of "valid" days from  given day, that you are kind of wasting your time using DatePeriod and DateInterval (both classes that usually I am a big proponent for their use).

Here this can be as simple as the following code:

function addWorkingDays(DateTime $from, $dayCount)
{
    $datetime = clone $from;
    while($dayCount > 0) {
        $datetime->modify('+1 weekday');
        if(!isHoliday($datetime)) {
            $dayCount--;
        }
    }
    return $datetime;
}

function isHoliday(DateTime $datetime)
{
    // holiday calculation logic here
    // return boolean
}

Note a few things here:

Here I require the caller to pass a valid DateTime object for $from.  Your current function just kind of assumes $from is valid value from which a DateTime object can be instantiated.  I would go ahead and remove all uncertainty from the function and require a DateTime object to operate against. In your usage example, it would be just as easy to pass new DateTime('now') to the function.
I have defined a separate function isHoliday() where one could define their holiday determination logic.  This also gives possible re-use outside the context of this function.  I wasn't quite sold on your holiday logic. I would think it would be rather trivial to actually get better data structure here to look up against (why the *- part?  that is not necessary to simply compare month and day)  Should you be using holiday dates as key in array instead of value to allow for direct lookup, vs. iterating array using in_array()? I did not specify an implementation of this function, as really, you might want to build a more robust listing of holidays well out into the future if you have any variable date holidays.
I renamed the function to perhaps better indicate what it is doing - adding working days to a given date, not getting the number of working days in some interval.


JavaScript date format string to php date format string convert

I don't see the need to do so much dynamic work.  I would establish a lookup array to access.  This will be clean, direct, and easy to maintain.  If the incoming format is not found, just fallback to m-d-Y using the null coalescing operator.
private $formatLookup = [
    'YYYY-MM-DD' => 'Y-m-d',
    'YYYY/MM/DD' => 'Y/m/d',
];

public function dateFormatStringConvert(string $format) : string
{
    return $this->formatLookup[$format] ?? 'm-d-Y';
}

With this setup, you never need to touch the processing method, you only need to maintain the lookup array.


Selection Sort implementation using modern C++

InputItr doesn't appropriately describe the iterator requirement of your selection sort, which multi-passes the range.  Consider naming the type after forward iterator.
Allow for custom overloads of swap by calling swap in an unqualified context.

    using std::swap;
    swap(*min, *first);

which is just std::iter_swap

    std::iter_swap(min, first);

You don't need to conditionally check if min is smaller than first.  Just swap.

  for (; first != last; ++first) {
    auto min = std::min_element(first, last);
    std::iter_swap(min, first);
  }

Your print function is just a reimplementation of std::copy.
Make sure you include everything (missing <string>).
Assert liberally. See the CPPCoreGuidelines.


Replacing a sequence of real numbers with another sequence

Let's split this up a bit; firstly, let's put the sequence filling code in its own function:

def populateSequence(length: Int): IndexedSeq[Double] = {
  for {
    i <- 1 to length
    _ = println("Enter sequence item ? " + i)
    item = readDouble()
  } yield item
}

This utilizes the a combination of for and yield - in this case, this returns an IndexedSeq[Double], but don't worry, you can treat this like a List (or simply convert it to one with a .toList if you really want to.

Our code structure then looks like this:

def main(args: Array[String]) {
  println("Enter Z number: ")
  val z = readDouble();

  println("Enter the length of sequence: ")
  val length = readInt();

  val seq = populateSequence(length)

Ok, where to from here? Well, in this case, instead of modifying substituteCount as we go, I'd rather just calculate it up front:

val substituteCount = seq count (_ > z)

To get our modified List (or IndexedSequence), we can use another for expression. Again, one thing to remember is that both for and if are expressions in Scala, so we can do this:

val modified = for {
  v <- seq
  item = if (v > z) z else v
} yield item

We can then print everything as usual:

println("Replacement count: " + substituteCount)
println("New sequence: " + modified.mkString(" "))


import pandas as pd

df = pd.read_clipboard(sep=',') # copied data from the gist

branches_of_sci = ['bio', 'chem', 'physics']

for branch in branches_of_sci:
    df[branch] = df.astype(str).sum(axis=1).str.contains(branch)

In my limited experience, for loops are almost always wrong when using Pandas.  The primary benefit of Pandas is vectorization, so using the built-in methods is typically best.

Here is a breakdown of the main function:

df[branch]  creates a new dataframe column
df.astype(str) converts all of the dtypes in the dataframe to strings
.sum(axis=1) concatenates all dataframe columns horizontally (i.e. axis=1)
.str.contains() use built-in string search (see docs)

Hopefully that helps.


Your implementation does not allow for an empty list.

It's a bit odd to only have the constructor which takes a node value.

You should probably implement the List interface.
You should look into generics instead of hard-coding your list to only take ints.
It looks like from looking at insert() that you are trying to create an ordered linked list.  However, append() does not.  (If you really want to define an ordered linked list, you can still use generics, but you'll have to use types which are children of Comparable).
In insert() and delete() you have some if-conditions followed by a while-loop.  My guess is that they can be merged in a single while-loop.  I was lazy and haven't tried doing it, so it might not be true.


Passing restored packages as artefacts in GitLab Continuous Integration

I had a wrong concept about GitLab artifacts. After a good read on GitLab docs, especially the section distinguishing artifacts and cache, I deduced that I should use cache instead of artifacts as it was designed precisely for storing restored dependencies. Artifacts are meant for passing build output and binaries.

I also removed the restore stage, placing the dotnet restore command in a global before_script. Cache can fail and in such scenario the script should gracefully fallback to default 'download-from-internet' behaviour. With --no-restore option enabled it would not happen. Thus, I removed that option from dotnet build command. It won't make a noticeable difference with successfully download cache as a dependency restore with already downloaded packages will execute in next-to-no-time.

Finally, I added cache key, which will keep cache bundles separate for branches and stages.

Updated script:

image: microsoft/dotnet:2.2-sdk

variables:
 SOURCE_CODE_DIRECTORY: 'src'
 BINARIES_DIRECTORY: 'bin'
 OBJECTS_DIRECTORY: 'obj'
 NUGET_PACKAGES_DIRECTORY: '.nuget'

stages:
  - build

cache:
 key: '$CI_JOB_STAGE-$CI_COMMIT_REF_SLUG'
 paths:
  - '$SOURCE_CODE_DIRECTORY/*/$OBJECTS_DIRECTORY/project.assets.json'
  - '$SOURCE_CODE_DIRECTORY/*/$OBJECTS_DIRECTORY/*.csproj.nuget.*'
  - '$NUGET_PACKAGES_DIRECTORY'

before_script:
  - 'dotnet restore --packages $NUGET_PACKAGES_DIRECTORY'

build:
 stage: build
 script:
  - 'dotnet build --no-restore'


A simple and clear approach would be to take an array of characters of the number, and reverse the array:

const reverse = function(inputNum) {
    const result = Math.sign(inputNum) * String(Math.abs(inputNum))
      .split('')
      .reverse()
      .join('');
    return result < -2147483648 || result > 2147483647 ? 0 : result;
};
console.log(reverse(-321));
console.log(reverse(1534236469));

The runtime is a little bit higher (92ms, not sure how precisely reliable the measurements are on LeetCode, they seemed all over the place), but in the vast majority of real-world situations, to write strong and maintainable code, one should first optimize clarity and readability, and then if the whole app isn't running as fast as would be ideal, run a performance test to identify bottlenecks and work on those particular bottlenecks.
Note the use of Math.sign to determine whether the number is positive or negative - it'll return -1 if the number is negative, and 1 if the number is positive, so it's probably a bit more appropriate for the situation.
Another approach without creating an intermediate array would be
let res = '';
for (let i = inputStr.length - 1; i >= 0; i--) res += inputStr[i];

With regards to your code:
Always declare your variables You're implicitly creating a global variable temp. Implicit creation of global variables will cause odd bugs when a function gets called when it's already in the process of running. Consider using a linter or strict mode or both to avoid these sorts of mistakes. (When declaring variables, prefer const, or use let when it needs to be reassigned.) On a similar note, your reverse function should be declared with const (not var).
Give variables meaningful names An argument named x and a variable named temp aren't very informative at a glance. How about calling them inputNum and sign instead?


Ugly code unit testing with PHPUnit and Doctrine2 (an ORM)

I decided that there was too much database access code in my UserPermissions class and split it into two classes.  The first class is now much easier to mock and the second class is just a wrapper for a doctrine query, which is probably almost pointless to mock.

class UserPermissions{

    protected $dbalUserProducts;

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

    /**
     * returns user's permissions for all products or specific product
     **/
    public function get($userId, $productId=NULL){

        $userProducts = $this->dbalUserProducts->get($userId, $productId);

        $result = [];

        for ($i = 0; $i < count($userProducts); $i++) {
            $up = $userProducts[$i];
            array_push($result, array(
                "product" => $up->getProduct()->getId(),
                "permissions" => $up->getPermissions(),
            ));
        }

        return $result;
    }
}

class UserProductQuery
{
    protected $em;

    public function __construct($entityManager)
    {
        $this->em = $entityManager;
    }

    public function get($userId=null, $productId=null){
        $qb = $this->em->createQueryBuilder();

        $qb->select('u')
           ->from('\MyProject\Entity\UserProduct', 'u');

        if ($userId) {
            $qb->andWhere($qb->expr()->eq('u.user', ':userId'));
            $qb->setParameter('userId',$userId);
        }
        if ($productId) {
            $qb->andWhere($qb->expr()->eq('u.product', ':productId'));
            $qb->setParameter('productId',$productId);
        }

        return($qb->getQuery()->getResult());
    }
}


Generating filesystem paths from a fixed string

Is there are reason you're not just doing:

path = os.sep.join([file[0:2], file[2:4], file[4:6]])

I think that my version is a little easier to parse (as a human), but if you need to extend the number of groups, your code is more extensible.

Edit: and if we're looking for things that are easy to read but not necessarily the best way to do it...

slash = os.sep
path = file[0:2] + slash + file[2:4] + slash + file[4:6]


Reasonable quality code. Here are a few comments:

1) I'd add a method drawNextCard, which encapsulates retrieval of the next card, and makes the code a bit more readable

def draw_next_card(drawn_cards):
    card = drawn_cards.pop(len(drawn_cards)-1)
    return readable_card_name(card)

def readable_card_name(short_card_name):
    return (short_card_name[0]+"["+short_card_name[1]+"]")

Then, for example, your flop() method would look like this:

def flop(self):
    (self.card1, self.card2, self.card3) = (draw_next_card(drawn_cards), draw_next_card(drawn_cards), draw_next_card(drawn_cards))
     self.flop = self.card1+ " - " + self.card2 + " - " + self.card3
     print (self.flop)

More readable, shorter, and on the way we fixed a copy/paste defect where you initialized card2 twice instead of card2 and card3.

2) You convert each drawn card to a readable representation. It's good for your debugging, but not so good for adding future functionality for actually calculating poker hands, and developing strategy. So, while my draw_next_card above returns a readable representation, you're better off creating a class Card, which has an __str__ method that has the same implementation as readable_class_name. The flop method would remain the same, but it will be much easier to extend the code.

3) Note that flop and river are copy/pastes. Both could just call draw_next_card. Also, while the flow and river are true to the game terms, they're not much benefit to software; you'd be better off collapsing flop, turn and river to a table_cards[5] vector. Once you start developing the actual game, it will make things much easier for you.

Hope this helps.


Bug

At the end of your program, the b array is all full of 1s, which means that you didn't find any primes.  The problem is here:

       num_t j = i;

Because you start your j loop at i, you will mark i (which is prime) as non-prime.  You should start your j loop at i*i instead (see below).

Don't get tricky

Why write this:

for(num_t i = 0; i ^ N; ++i)

when you can write this:

for(num_t i = 0; i < N; ++i)

I had to stare at your code for a long time just to figure out whether it was correct, for a simple loop!

Also, you did it here:

for(num_t i = 3; i ^ 1 ^ N; i += 2) {

which should be:

for(num_t i = 3; i < N; i += 2) {

You can afford to waste 2 bytes

Here, you use index-2 to save 2 bytes:

    if(!b[i - 2]) {
        // printf("%llu\n", i);
        const num_t increment = i << 1;
        num_t j = i;
        while(j < N) {
            b[j - 2] = 1;
            j += increment;
        }
    }

There's no need to save 2 bytes.  Just use b[index] instead of b[index-2].  You already allocated the full array anyways.

Speed improvements

There are three things I can see that could speed up your program:

In your j loop, you can start j at i*i instead of just i.  All non-primes less than i*i will already be marked.
You can stop the i loop at sqrt(N) instead of at N, because once you reach sqrt(N), the second loop won't mark any more entries.
Since you are finding primes up to 10^9, you are using 1GB of memory for the b array.  You should get better performance if you use less memory, because the processor cache will be utilized more effectively if your array is smaller.

a) You can only track odd numbers, which will reduce your memory usage to 1/2 of the original (512MB).

b) You can use 1 bit per number instead of 1 byte per number.  This will reduce your memory to 1/8 of the original.  Combined with (a), it will be 1/16 the original, or 64MB.  This is a much better than 1GB.

Example using 1 bit per odd number

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#define N        1000000000

int main(void)
{
    int       arraySize = ((N + 63)/64 + 1) * sizeof(uint32_t);
    uint32_t *primes    = malloc(arraySize);

    // Each bit in primes is an odd number.
    // Bit 0 = 1, bit 1 = 3, bit 2 = 5, etc.
    memset(primes, 0xff, arraySize);

    // 1 is not a prime.
    primes[0] &= ~0x1;

    int sqrt_N = sqrt(N);
    for(int i = 3; i <= sqrt_N; i += 2) {
        int iIndex = i >> 6;
        int iBit   = (1 << ((i >> 1) & 31));
        if ((primes[iIndex] & iBit) != 0) {
            int increment = i+i;
            for (int j = i * i; j < N; j += increment) {
                int jIndex = j >> 6;
                int jBit   = (1 << ((j >> 1) & 31));
                primes[jIndex] &= ~jBit;
            }
        }
    }

    // Count the number of primes in order to verify that the above worked.
    // Start count at 1 to include 2 as the first prime, since we are only
    // going to count odd primes.
    int count = 1;
    for (int i = 3; i < N; i += 2) {
        int iIndex = i >> 6;
        int iBit   = (1 << ((i >> 1) & 31));
        if (primes[iIndex] & iBit)
            count++;
    }
    printf("%d\n", count);

    free(primes);
    return 0;
}

Edit: Even less memory usage

Pete Kirkham suggested using even less memory by using 2 out of every 6 numbers.  In other words, using 1 bit per every 3 numbers instead of 1 bit per every 2 numbers.  At first I was skeptical because this required using a division in the inner loop.  However, after coding it up, it turned out to be faster.  The code is quite a bit trickier however, because the inner loops need to avoid any multiples of 3, because all multiples of 3 are no longer in the primes array:

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#define N        1000000000

int main(void)
{
    int       arraySize = (N/24 + 1);
    uint32_t *primes    = malloc(arraySize);

    // The bits in primes follow this pattern:
    //
    // Bit 0 = 5, bit 1 = 7, bit 2 = 11, bit 3 = 13, bit 4 = 17, etc.
    //
    // For even bits, bit n represents 5 + 6*n
    // For odd  bits, bit n represents 1 + 6*n
    memset(primes , 0xff, arraySize);

    int sqrt_N = sqrt(N);
    for(int i = 5; i <= sqrt_N; i += 4) {
        int iBitNumber = i / 3 - 1;
        int iIndex = iBitNumber >> 5;
        int iBit   = 1 << (iBitNumber & 31);
        if ((primes[iIndex] & iBit) != 0) {
            int increment = i+i;
            for (int j = i * i; j < N; j += increment) {
                int jBitNumber = j / 3 - 1;
                int jIndex = jBitNumber >> 5;
                int jBit   = 1 << (jBitNumber & 31);

                primes[jIndex] &= ~jBit;

                j += increment;
                if (j >= N)
                    break;

                jBitNumber = j / 3 - 1;
                jIndex = jBitNumber >> 5;
                jBit   = 1 << (jBitNumber & 31);

                primes[jIndex] &= ~jBit;

                // Skip multiple of 3.
                j += increment;
            }
        }
        i += 2;
        iBit <<= 1;
        if ((primes[iIndex] & iBit) != 0) {
            int increment = i+i;
            for (int j = i * i; j < N; j += increment) {
                int jBitNumber = j / 3 - 1;
                int jIndex = jBitNumber >> 5;
                int jBit   = 1 << (jBitNumber & 31);

                primes[jIndex] &= ~jBit;

                // Skip multiple of 3.
                j += increment;

                j += increment;
                if (j >= N)
                    break;

                jBitNumber = j / 3 - 1;
                jIndex = jBitNumber >> 5;
                jBit   = 1 << (jBitNumber & 31);

                primes[jIndex] &= ~jBit;
            }
        }
    }

    // Initial count includes 2, 3.
    int count=2;
    for (int i=5;i<N;i+=6) {
        int iBitNumber = i / 3 - 1;
        int iIndex = iBitNumber >> 5;
        int iBit   = 1 << (iBitNumber & 31);
        if (primes[iIndex] & iBit) {
            count++;
        }
        iBit <<= 1;
        if (primes[iIndex] & iBit) {
            count++;
        }
    }
    printf("%d\n", count);

    free(primes);
    return 0;
}

I'm sure the variant that works on multiples of 30 would be even faster than this, although the code would be even more complicated.

Timings

Here are the speeds of the various programs I ran on my computer:

Original program        : 13.33 seconds
OP fixed (i*i, sqrt(n)) :  7.75 seconds
1 bit per odd number    :  3.90 seconds
1 bit per 3 numbers     :  2.77 seconds

Note that I did not include the time it took to count the primes to verify the result.   I modified each program to count the number of primes just to make sure that they all worked, which is how I discovered that the original program had a bug in it.


Sample size, P-values (its relationship), and data visualization with plots. ggplot and T test

In this code you do not need the loop:

sample <- 1:nsim
t_result <- (mean(ctrl_mean)-mean(treated_mean)) /
  sqrt((ctrl_sd^2/(sample))+(treated_sd^2/(sample)))
# OR:
t_result <- (mean(ctrl_mean) - mean(treated_mean)) /
  sqrt((ctrl_sd^2 + treated_sd^2) / sample)

why the set seed?


-(id)pop{
    id lastObj = [stack lastObject];
    [stack removeLastObject];
    return lastObj;
}

Not sure if you are using ARC, but without ARC this is a potential use-after-free bug.  If you are not using ARC you should consider:

-(id)pop{
    id lastObj = [stack lastObject];

    if (lastObj)                         // < -- now checking for nil
    {
       [[lastObj retain] autorelease];   // < -- this line added

       [stack removeLastObject];
    }
    return lastObj;
}

(This also assumes that the objects in the stack are NSObjects, but I believe NSMutableArray makes the same assumption...)

This bumps the ref count up so that the next line (which will cause the NSMutableArray to release its reference to the object) does not end up deallocating the object.

Update on second reading:

Also, what do you do when lastObj is nil (i.e. too many pops)?  Doesn't seem like you've handled that case.


Java/Swing GUI code/layout, am I doing this wrong?

Your code seems perfectly fine!

However...

If all of this code is in the same block (e.g., a constructor or a layout builder method), I would recommend that you break up the layout code into smaller functions. That will improve readability and code structure a bit.

Also, you should definately familiarize yourself with some GUI builders for Java (in my case it was WindowBuilder for Eclipse). Writing layout code by hand can be a pain and a source of bugs that you won't be able to resolve easily.


Your logic is correct.

You may use let instead of let* since the value of one binding does not depend on the value of another binding.

Since efficiency is important, you can cut back on the number of comparisons as well.  For example, if u-x is negative, then l-x is also negative and need not be tested.  For this reason, the functions negative?, positive? and straddles-zero? are not necessary.  Instead, you can simply use nested ifs:

(if (< u-x 0)
    ; x is in R < 0
    (if (< u-y 0)
        ; y is in R < 0
        ...
        (if (< l-y 0)
            ; y contains 0
            ...
            ; y is in R >= 0
            ... ))
    (if (< l-x 0)
        ; x contains 0
        ...
        ; x is in R >= 0
        ... ))


Fractional Knapack as asked in an interview

float val = 0;
        while (queue.size() > 0) {
            if (capacity == 0) return val;
            Pair max = queue.poll();
            float a = Math.min(max.weight, W);
            val += a * (max.value / max.weight);
            if (max.weight - a > 0) // to prevent division by zero
                queue.add(new Pair(max.value, max.weight - a));
            capacity -= a;
        }
        return val;

Consider

        float val = 0;

        while (!queue.isEmpty()) {
            Pair max = queue.poll();
            if (max.weight < capacity) {
                val += max.value;
                capacity -= max.weight;
            } else {
                return val + capacity * (max.value / max.weight);
            }
        }

        return val;

The canonical way to check if a collection is empty is to call the isEmpty() method.

We check that the capacity hasn't been reduced to zero before the end of the loop rather than at the beginning.  Note that a side effect of this is that we don't care about passing 0.0.  In the original code, floating point rounding could allow you to pass the equality check.

Rather than take Math.min, we compare max.weight and capacity.  This simplifies the logic, as we don't have to multiply and divide by the same value in the expected case.  We only do that for the final item.


Printing bowTie pattern in efficient and pythonic way

Don't use a class, there's no need.
You can remove the tmplst.append if you move the comprehensions into the th.append.

To do this you can use (i + idx) % 2 == 1 as the check. And tmplst = [xrange(1,row + 1), xrange(m, m-row, -1)].
It doesn't make sense to build a set, to then convert it to a list. Sets have \$O(1)\$ lookup where lists have \$O(n)\$.
You don't need get_list, just use a comprehension.

This can get something like:

def bow_tie(self, size=5, fill_value='*', empty_value=' '):
    star = fill_value
    dot = empty_value
    center_row = size * 2 - 1
    th = [
        {
            j
            for nums in (
                xrange(1, i + 2),
                xrange(center_row, center_row - i - 1, -1)
            )
            for j in nums
            if (j + i) % 2 == 1
        }
        for i in range(size)
    ]
    th += th[len(th) -2::-1]

    return [
        ' '.join([
            star if i in indexes else dot
            for i in range(1, size * 2)
        ])
        for indexes in th
    ]

However, this isn't that good an approach. Instead you can make a list containing the pattern. And show a 'view'. The view that you want could be:

     *
    **
   ***
  ****
 *****
******

To achieve this, you can make the following list:

'     ******'

With the following moving view:

#     *######
##    **#####
###   ***####
####  ****###
##### *****##
######******#

You can also invert the view to get the other side of the bow tie. And so using the above, we just need to think of what the pattern of the list needs to be for your bowtie.

Since it's pretty much the same as the above, but with a space in-between the dots you could use something like:

'     * * * '

And to create that, just make the first n chars space, with the following n chars flip between space and star:

face = [empty_value] * (size - 1) + [fill_value, empty_value] * (size // 2 + 1)

After this combine the above slider, and chain the top and bottom starts, and you should get:

from itertools import chain

def bow_tie(size=5, fill_value='*', empty_value=' '):
    face = [empty_value] * (size - 1) + [fill_value, empty_value] * (size // 2 + 1)
    starts = chain(range(size), reversed(range(size-1)))
    for i in starts:
        yield ' '.join(face[i:i+size][::-1][:-1] + face[i:i+size])


Find the 4 best parameters of a function to have the best cumulative sum

Answer, part one
It looks like about half the loops can be avoided by doing the True and False cases at the same time.  These differ only by the multiplication by -1 at the end of fct.  That suggests that results of of a True invocation can be used to shortcut the computations of the immediately following invocation of fct.
Is there a reason to not cache the results of the several array accesses?  That is, for example, df[name_a], df[name_b], and others?
Can the apply and lambda be avoided?  This seems overly complex (meaning, slow) way to perform the computation.
I presume the print invocation is not there usually.  IO in the inner loop would slow things down considerably.
Answer, part 2
Sample code.  This runs for me, but I haven't verified that it produces exactly the same results.
I made two kinds of updates: Values which were shared across loops were lifted to the most common loop.  The True and False cases were collapsed into a single function call which returns the True and False results using multiple values.
Ignore my comment re: apply.
My gut tells me that at least the innermost shift invocation ought to be unnecessary, but I haven't figured how to write a correct apply that would remove it.  (I need the apply iteration index to be passed in as an extra parameter.)
I added a number of print statements for debugging which you will want to remove.
import pandas as pd
import numpy as np

def fct_tf(data, name_a, name_b, param_a, param_b, param_c, df_common, df_shift):
    "Compute results for two sets of parameters"

    df_false = df_common.copy()

    # Lift one of the shifts up a loop.
    # Still working on removing the shifts altogether.
    # df_false['name_b_delta'] = df_false[name_b].shift(2+param_a)-df_false[name_b].shift(2+param_a+param_b)
    df_false['name_b_delta'] = df_shift - df_shift.shift(param_b)
    df_false['is_ok'] = df_false['name_b_delta'].apply(lambda x : np.sign(x+(-param_c)))

    df_false['results'] = df_false['is_ok'] * df_false['pct']
    df_false['cumul_results'] = df_false['results'].cumsum()

    df_true = df_false.copy()
    df_true['results'] = -1 * df_false['results']
    df_true['cumul_results'] = -1 * df_false['cumul_results']

    return df_true, df_false

def fct(data, name_a, name_b, param_a, param_b, param_c, param_d):
    "Compute results for one set of parameters"

    df = data.loc[(data[name_a].notnull()) & (data[name_b].notnull()),[name_a, name_b]]

    df['pct'] = df[name_a].pct_change()
    df['name_b_delta'] = df[name_b].shift(2+param_a)-df[name_b].shift(2+param_a+param_b)
    df['is_ok'] = df['name_b_delta'].apply(lambda x : np.sign(x+(-param_c)))

    if param_d:
        df['results'] = df['is_ok'] * (-1) * df['pct']
    else:
        df['results'] = df['is_ok'] * df['pct']

    df['cumul_results'] = df['results'].cumsum()

    return df

def compute(data, names_a, names_b):
    "Compute results ..."

    df_line= []
    df_index = []

    for name_a in names_a :
        print('name_a: ' + name_a)
        for name_b in names_b :
            print('name_b: ' + name_b)

            # 'df_common' will have just one column if the names are the same.
            # Then, an exception occurs when invoking 'pct_change()'.
            if ( name_a == name_b ):
                continue

            # This part of the results data is common across the parameters.
            df_common = data.loc[(data[name_a].notnull()) & (data[name_b].notnull()),[name_a, name_b]]
            print('Common data:')
            print(df_common)

            # The percent change is also common.  Note that the values are not free from
            # a dependence on 'name_b', since the null check can change which rows are selected.
            # That means this value cannot be lifted to the 'name_a' loop.
            df_common['pct'] = df_common[name_a].pct_change()
            print("Common data[pct]:")
            print(df_common['pct'])

            for param_a in range(0,15):
                # Reduce the number of shifts
                # In theory, this shift should be avoidable, but I'm still figuring
                # how to remove it.
                df_shift = df_common[name_b].shift(2+param_a)

                for param_b in range(1,15):
                    for param_c in range (-2, 3, 1):
                        # The computations for 'False' and 'True' are the same, except
                        # for a change in sign.
                        # for param_d in [True, False]:
                            # df = fct(data, name_a, name_b, param_a, param_b, param_c/1000, param_d)
                            # df_index.append(f"{name_a}-{name_b}")
                            # df_line.append([df['cumul_results'].iloc[-1], param_a, param_b, param_c, param_d])

                        df_true, df_false = fct_tf(data, name_a, name_b, param_a, param_b, param_c/1000, df_common, df_shift)

                        df_index.append(f"{name_a}-{name_b}")
                        df_line.append([df_true['cumul_results'].iloc[-1], param_a, param_b, param_c, True])

                        df_index.append(f"{name_a}-{name_b}")
                        df_line.append([df_false['cumul_results'].iloc[-1], param_a, param_b, param_c, False])

    results = pd.DataFrame(index=df_index, data=df_line, columns=['final result', 'param_a', 'param_b', 'param_c', 'param_d'])

    return results


Parsing data from XML in C#, filtering, categorizing in LINQ, displaying on Chart control

For the LINQ query at the end SelectMany is your friend.

You should be able to achieve your desired results in a single query:

var dateOfInterest = DateTime.Now; // just put in whatever date interests you

var categoryTotals = receipts
         // filter receipts by the desired month
        .Where(r => IsWithinSameMonthAndYear(r.Date, dateOfInterest))
        // select all products from all filtered receipts as a flat list
        .SelectMany(r => r.Products)
        // group the products by their category
        .GroupBy(p => p.Category)
        // turn into a dictionary keyed of the category key and the value is the weighted sum of the product quantities
        .ToDictionary(g => g.key.Key, g => g.Sum(p => p.Quantity * p.Price));

Little helper method:

// returns true if first is within the same month and year as second
private bool IsWithinSameMonthAndYear(DateTime first, DateTime second)
{
    return first.Year == second.Year && first.Month == second.Month;
}


I ran a few examples through the code and I have made the following assumptions:

the code calculates the minimum amount of coins needed to produce the user's input
the user can enter in a custom coin and it will use that as part of its calculations

Instead of using a matrix, I just found the highest coin which can be used to make change, then subtracted it from the total user inputted amount, and repeated it until there was no change left.

coins = [50000, 20000, 10000, 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1]

coinToAdd = int(input("Enter in coin to add to coins:"))
userMoney = int(input("Enter in coin to calculate change:"))
coins.append(coinToAdd)
coins.sort(reverse=True)
totalCoins = 0
while [j for j in coins if userMoney >= j]:
  userMoney = userMoney - [j for j in coins if userMoney >= j][0]
  totalCoins = totalCoins + 1

print(totalCoins)


Find the highest frequency of messages inside a time slot of 24 hours

First of all: python has not native array.

In other words Message is a list and every time you type Message[n] you will pay O(n) computational cost to execute it.

The worst case analysis of your code computational complexity is O(n^3) where n is total number of messages.

Avoid the use of list index in python for cycle and use iterators or dictionary instead. In your case you scan the list item per item so my first try is to use iterator that should give to you an O(n) computational complexity.

Now after took in account that use lists as array in python is the best way to increase computational complexity, we can take a look to the alternatives:

Use list as list by and rewrite the code by use Iterators and itertools
Use dictionary instead lists
Use numpy.array instead lists

numpy.array maybe is little bit overkill approach; in this case iterators are always the best because in your algorithm you scan the message as list, but use dictionary can be implemented without change your algorithm.

The Dictionary way

First of all replace Messages list by a dictionary where keys are the list index. To do it just replace

Messages = [x[0] for x in Messages]

by

Messages = {index:x[0] for index,x in enumerate(Messages)}

Messages now is a dictionary where access to Messages[k] have an amortized constant cost. So the same syntax that you used to get elements from your list now can be used on dictionary but its cost doesn't depend from the number of messages at all.

The only thing that we must fix now is the cycle that should follow index order (key array are not ordered for standard dictionary). To do it replace the list iteration for message in Messages by a cycle for each index from 0 to len(Messages) and message variable become Messages[index]. In other words instead of for message in Messages: write

for index in range(len(Messages)):
    message = Messages[index]

By that simple trick you algorithm become O(n)... Is it magic? No. Dictionary are amortized O(1) for access, inserting and delete operation and in python are very well optimized because almost everything in python is based on dictionary.

What do you pay by use dictionary is memory and constants. So your next step could be rewrite it by use iterator but just dictionary should decrease execution time drastically.

Use iterator means change your algorithm deeply and maybe you don't really need it even I think it could be a very good exercise.


Read a single int from an optional .properties file

you could at least get rid of the if by combining the exceptions:

int port;
try ( InputStream webserverProperties = WebServer.class.getResourceAsStream( "webserver.properties" ) ) {
        Properties p = new Properties();
        p.load( webserverProperties );
        String listen = p.getProperty( "listen", "443" );
        port = Integer.parseInt( listen );
}
catch ( NumberFormatException|NullPointerException e ) { port = 443; }
finally {}

or ignore exceptions at all:

int port= 443;
try ( InputStream webserverProperties = WebServer.class.getResourceAsStream( "webserver.properties" ) ) {
        Properties p = new Properties();
        p.load( webserverProperties );
        String listen = p.getProperty( "listen", "443" );
        port = Integer.parseInt( listen );
}
catch ( Exception e ) {}
finally {}


Commit the working directory to different branch and switch back

Putting it through shellcheck.net results in quite a lot of cleanups.

Apart from the issues raised there, I'd suggest that at the end of your script, you might want to git stash pop instead of git stash apply when restoring your state.

Inside the function body, you may use local to declare the BEFORE variable. While local is not POSIX compliant, all of GNU and BSD compliant shells support the local keyword.


Balancing Brackets Algorithm: Stack Data Structure

The code looks reasonably clean, IMO. I assume that it is purposely ES5?

I don't know about Stack as it's not a ES5 standard API (that I know of).

You are not returning any value.  There is no need for ? true : false — just do return stack.length() === 0;.

Some code that you can consider, in ES5.

var completes = ['()', '[]', '{}'];
var open = completes.map(function(complete) {
  return complete.charAt(0);
});
var close = completes.map(function(complete) {
  return complete.charAt(1);
});

function isBalanced(arr) {
  var stack = [];
  arr.forEach(function(curr) {
    if (open.indexOf(curr) !== -1) {
      stack.push(curr);
    }
    if (close.indexOf(curr) !== -1) {
      var last = stack.pop();
      if (completes.indexOf(last + curr) === -1) {
        stack.push(last);
      }
    }
  });
  return stack.length === 0;
}

console.log(isBalanced(['{', '(', ')', ']']));
console.log(isBalanced(['[', '(', ')', ']']));


Naming

The enum Cell defines Empty, Circle and Cross. This values aren't cells in terms of an object, they are more like types.

For example: Empty is not a cell, but a cell can be empty

You can rename Cell to CellType to make it more clear.

Comments

Comments are a good documentation. You did a great job with the <summary>-tag. But the comments like // Row 1, // Row 2, // Clm 3 are not so good..

Robert C. Martin, who wrote the book "Clean Code" and many more, sad

  Don’t Use a Comment When You Can Use a Function or a Variable

Introduce Methods

We can wrap the if-statements into methods

bool IsFirstRowComplete(CellType cellType) {
    if (this.cells[0, 0] == cellType && this.cells[0, 1] == cellType && this.cells[0, 2] == cellType) {
        return true;
    }
    return false;
}

bool IsSecondRowComplete(CellType cellType) {
    if (this.cells[1, 0] == cellType && this.cells[1, 1] == cellType && this.cells[1, 2] == cellType) {
        return true;
    }
    return false;
}

// ...

Make them less complex

Since these methods return a Boolean we can return the boolean-expression itself

bool IsFirstRowComplete(CellType cellType) {
    return this.cells[0, 0] == cellType
           && this.cells[0, 1] == cellType
           && this.cells[0, 2] == cellType
}

bool IsSecondRowComplete(CellType cellType) {
    return this.cells[1, 0] == cellType
           && this.cells[1, 1] == cellType
           && this.cells[1, 2] == cellType
}

// ...

Remove Duplication

The new methods IsFirstRowComplete and IsSecondRowComplete looks very similar. We can extract the main logic and wrap it into its own method.

bool IsRowComplete(CellType cellType, int row) {
    return this.cells[row, 0] == cellType
           && this.cells[row, 1] == cellType
           && this.cells[row, 2] == cellType
}

// ...

If you like you can now wrap this method into IsFirstRowComplete and so on

bool IsFirstRowComplete(CellType cellType, int row) {
    return IsRowComplete(cellType, 0);
}

// ...

Introduce more Methods

We could finish here.. But we can make the code more clear if we wrap each check into a method

bool IsARowComplete(CellType cellType) {
    return IsFirstRowComplete(cellType, 0)
           || IsSecondRowComplete(cellType, 1)
           || IsThirdRowComplete(cellType, 2);
}

bool IsAColumnsComplete(CellType cellType) {
  return IsFirstColumnComplete(cellType, 0)
         || IsSecondColumnComplete(cellType, 1)
         || IsThirdColumnComplete(cellType, 2);
}

// ...

After the Refactoring

bool IsGameOver(CellType cellType) {
    return IsARowComplete(cellType)
           || IsAColumnComplete(cellType)
           || IsAHorizontalComplete(cellType)
}

Maybe a Bug

If the method isGameOver gets called with a CellType of type Empty it could return true

So maybe you need to check if the cellType is not Empty


REST service to list new, continuing, and terminated subscribers during some period

This is one way of implementing it.
Whether it's right or not depends on many conditions,
and we could only speculate.
Here are some example problems anyway,
that could be serious issues:

The current solution is inefficient for large lists, because for example, for list1.retainAll(list2) the worst case complexity is \$O(N M)\$ where \$N\$ and \$M\$ are the sizes of the two lists. (For more details, see the source code of ArrayList.retainAll. You could make that \$O(N)\$ by converting list2 to a Set.
The current solution modifies request.getStart() and request.getEnd(). Maybe that's not ok, then the current solution should be adjusted to work with copies instead.

On the other hand,
a good thing about the current solution is that it's short and idiomatic,
and it doesn't waste memory (at the expense of CPU).

Lastly,
a minor issue is that the comments are pointless,
they only state the obvious.
The code would be easier to read if you made those lines empty.


I have a couple thoughts:

Be explicit in defining your constant called url, i.e.

Private Const url As String = "https://www.houzz.com/professionals/"

Be consistent in how you group your variable declarations. You've grouped some, but not others.

I'm thinking you can have one function that returns responseText each time you do this:

With http
    .Open "GET", url, False
    .send
    html.body.innerHTML = .responseText
End With

...and for htm, and hmm

When you use With, End With but only have one line between them, the excessive nesting doesn't aid readability and defeats the purpose of using With, End With. IMHO it would be clearer to just name it out explicitly.I'm thinking something along these lines:

Set foo = gist.getElementsByClassName("profile-full-name")
If foo.Length Then Cells(x, 1) = foo.Item(0).innerText

The code inside For Each post in Topic should be indented like you indented For Each gist In hmm.getElementsByClassName("container profile-carded").