The big performance hit probably comes in this block of code, where you don a bunch of array manipulations and looping:

all_word = [letter_list[start:end+1] for start in xrange(l)
                                     for end in xrange(start, l)]
for array in all_word:
    if array[0] in vowel:
        person_b_words.append(array)
for array in all_word:
    if array[0] in consonants:
        person_a_words.append(array)
if len(person_a_words) == len(person_b_words):
    print 'Draw'
if len(person_a_words) > len(person_b_words):
    print person_a_name, len(person_a_words)
if len(person_b_words) > len(person_a_words):
    print person_b_name, len(person_b_words)

Appending to an array is a (relatively) expensive operation, as is looping over a list. I can see a number of optimisations here. [Edit: I wrote these in the order I thought of them; the big performance gain comes on the last item. I'm leaving the remaining items because they're still instructive, even if not directly applicable here.]

Only loop over all_word once. You can check for starting with a consonant and vowel in the same iteration of the loop:

for array in all_word:
    if array[0] in vowel:
        person_b_words.append(array)
    elif array[0] in consonants:
        person_a_words.append(array)

We've just cut out an iteration over all_word. If all_word is large, that will be a significant saving.
Don't store the words in a list, just the count. All you care about is the relative number of words in each list; the words themselves don't matter. It's much easier to increment an integer than mutate a list, so consider the following:

person_a_words = 0
person_b_words = 0
for array in all_word:
    if array[0] in vowel:
        person_b_words += 1
    elif array[0] in consonants:
        person_a_words += 1

and then you can compare the two integers at the end. That's bound to be a performance saving.
Don't construct all_word as a list; use a generator. If you replace the square brackets with parens:

all_word = (letter_list[start:end+1] for start in xrange(l)
                                     for end in xrange(start, l))

then this becomes a generator comprehension instead of a list comprehension. This means it only creates the elements as they're needed by the for loop; it doesn't create them all in memory before continuing.

Using generators instead of lists is a really good way to reduce occupancy and speed up programs.
Do you even need to use all_word? For each value of start, the first letter of the resulting words will be the same, and this gives you (l - start) different words. You don't actually need to create the words; you just care about their initial letter, and how many distinct words they create.

You could just add the number of distinct words to each person's score directly:

person_a_words = 0
person_b_words = 0
for idx, letter in enumerate(letter_list):
    if letter in vowel:
        person_b_words += len(letter_list) - idx
    else:
        person_a_words += len(letter_list) - idx

That is substantially faster: I just ran this with a 1.5m character string, and it finished in ~1.5s.

Other non-performance related comments:

Don't use str as a variable name; overriding builtins is bad practice.
You've imported the string, sys and itertools modules, but you never use any of them. Why?
PEP 8 requires a space after commas in a list; you should add this in vowel and consonants.
You can get the individual letters of a string by calling list() on it. These calls are equivalent:

letter_list = [a for a in my_string]
letter_list = list(my_string)

although in this case, you don't need to coerce to a list first – you can iterate over the characters of a string directly.
There's no need to assign the length of letter_list to a variable, especially not one with as undescriptive a name as l. It just makes your code harder to read.
The name of your function isn't particularly helpful. Ideally it should give me some idea of what the function does. There should also be a docstring to explain the result.
I would rename the person_a* and person_b* variables to be consonant* and vowel*, respectively – that will make the code easier to read. A and B don't really mean anything (and as evidence, I got them the wrong way round when I first wrote that sentence).
Your function is doing some work (finding out whether there are more vowel sub-words or consonant subwords) and printing to screen (the result). It would be better to separate this into two functions: one that does the work, the other does the result.

That makes it easier to reuse the work of vowels vs. consonants.
To aid readability, I'd keep the same order of variables when you do the comparison at the end. i.e.

if vowel_count > consonant_count:
    print("Vowels victorious!")
elif vowel_count < consonant_count:
    print("Consonants champion!")
else:
    print("Draw!")


You could replace the while with a for-each loop. That will get rid of the otherwise unused pos variable, and make the code slightly more compact and idiomatic.

for (char c : S.toCharArray()) {
    // ...
}

Instead of printing the output in the same function that does the main computation, you could return the string result, to minimize the function's responsibilities.

Other than these minor points, the code is fine.


Check if a range in Excel contains DataValidation

I'd recommend caution re: using On Error statements in utility functions like this. Any custom error handling in the main procedure (ie "On Error GoTo lineNum") will be overwritten by this function, so you'll have to remember to manually change it back any time you use the function in a procedure with custom error handling.

My advice would be to pick a personal rule-- either "Never use On Error statements in utility functions, only in main procedures" or "Only use On Error statements in utility functions, never in main procedures"-- and stick to it.

If you do use them, make sure that you switch back to On Error GoTo 0 for all exits from the function. In the first portion of the "IF" block in your current code, you only switch back if the function returns null:

On Error Resume Next
Dim singleCell As Range
For Each singleCell In cell
    '...do stuff, then

    If cellWithValidationFound And cellWithoutValidationFound Then
        On Error GoTo 0
        HasValidation = Null
        Exit Function
    End If
Next

'On Error GoTo 0 needs to be added here
HasValidation = cellWithValidationFound

In this case, it's possible to avoid the "On Error" statements entirely by using the SpecialCells and Intersect methods. Only caveat is that it assumes that your range's parent worksheet contains at least one blank cell:

Function hasValidation(rng As Range) As Variant

    'Find first empty cell in ws and add validation
    'This ensures that at least 1 cell in ws contains validation
    Dim emptyCell As Range
    Set emptyCell = rng.Parent.Cells.SpecialCells(xlCellTypeBlanks).Cells(1)
    emptyCell.Validation.Add Type:=xlValidateList, Formula1:="1"

    'Get range of all cells in ws with validation, then remove validation from empty cell
    Dim validationCells As Range
    Set validationCells = rng.Parent.Cells.SpecialCells(xlCellTypeAllValidation)
    emptyCell.Validation.Delete

    'Get intersection of validation cells and range being tested
    Dim rngUnion As Range
    Set rngUnion = Intersect(rng, validationCells)

    'Determine whether entire/partial range has validation and return value
    If rngUnion Is Nothing Then
        hasValidation = False
    ElseIf rngUnion.Count = rng.Count Then
        hasValidation = True
    Else
        hasValidation = Null
    End If

End Function

It'd be possible to design a slightly safer version that accounts for sheets with no blank cells, but that scenario is so unlikely that it's probably not worth the effort.

EDIT: Actually, it turns out that Range.SpecialCells(xlCellTypeBlanks) is way worse than I thought. Not only is it obscenely slow for large ranges, it also only searches the Used Range, not the entire sheet. So you may have no option but to use error handling.

Luckily, you can use the same basic format while incorporating On Error. Since it uses Intersect instead of looping through cells, it should be faster than your version. Also, rather than returning Null in mixed cases, it uses optional parameter that alters how the function treats ranges with a mix of validation/no validation. That's just a stylistic preference, I'm not a big fan of Null. Here's my final version:

Function hasValidation(rng As Range, Optional entireRange As Boolean = False) As Boolean

    'Get range of all cells in sheet containing validation
    On Error Resume Next
    Dim validationCells As Range
    Set validationCells = rng.Parent.Cells.SpecialCells(xlCellTypeAllValidation)
    On Error GoTo 0

    'If no cells contain validation, return False and exit
    If validationCells Is Nothing Then
        hasValidation = False
        Exit Function
    End If

    'Get intersection of validation cells and range being tested
    Dim rngUnion As Range
    Set rngUnion = Intersect(rng, validationCells)

    'Determine whether entire/partial range has validation and return value
    If rngUnion Is Nothing Then
        hasValidation = False
    Else
        hasValidation = IIf(rngUnion.Count = rng.Count, True, Not entireRange)
    End If

End Function


I think that the approach of the question lacks only a better usage of the API of java.nio.file.Path.

Using the old java.io.File seems very ugly nowadays, when we have java.nio.*, where all the stuff like file separators is supported much better.

// ...
String originalFile = "/path/to/myFile.txt";
Path originalPath = Paths.get(originalFile);
String backupFileName = buildBackupFileName(originalPath.getFileName().toString());
Path backupPath = originalPath.getParent().resolve(backupFileName);
Files.move(originalPath, backupPath); // add options if necessary
// ...

private static String buildBackupFileName(String fileName) {
  String backupSuffix = "_old"; // or move it in a static constant
  int lastDotIndex = fileName.lastIndexOf(".");
  if (lastDotIndex > -1) {
    return fileName.substring(0, lastDotIndex) + backupSuffix + fileName.substring(lastDotIndex);
  }
  return fileName + backupSuffix;
}

Other ways to build the backup file name: use StringBuilder or String.format, with or without the above FilenameUtils.


One comment I might suggest is your hard reference to mass_message, consider passing that in as part of your event data, as it makes the code more re-usable (Several instances of your editor on a page?)

A thought to consider is to swap your hard b and i tags to instead define css classes to be used? This will give you code re-use, if you had bold and italic defined in a css, you could use the above code you have to simply change the class on click instead, allowing you to do more jazzy stuff, borders and such, or be very clever and have specific things you define, maybe floats and margins/padding etc. You could use span as a first try and set the class of the span equal to the specified format :)


Contains all elements and duplicates are taken into account

The best way would be to change data structure. Instead of using a List<Int> you can use a Map<Int, Int>. If you want to have a List<Int> in the beginning, that's ok, you just need to convert it to a Map<Int, Int> and compare the maps.
Using the nice Kotlin methods in the stdlib, we can make the code into this:
fun <T> containsAllSameCount(toCheck: List<T>, expected: List<T>): Boolean {
    val toCheckCountMap = toCheck.groupBy { it }.mapValues { it.value.size }
    val expectedCountMap = expected.groupBy { it }.mapValues { it.value.size }
    return expectedCountMap.all { toCheckCountMap[it.key] == it.value }
}

I have also added generics here because the same logic applies whether it's a List<Int>, List<String> and so on.
Some other notes:

Use JUnit for proper tests.
The main method in Kotlin does not need to be declared with the args, simply fun main() { will do.
Use val instead of var whenever possible.
Instead of .filter and then checking the size, use .count


p = malloc(n*sizeof *p);

This is dangerous if n gets large, because the multiplication could overflow. After the overflow, too little memory has been allocated but code will continue without detecting the error.

This is especially dangerous if n comes from untrusted source, such as some file format or remote user. Then it gives attacker easy way to overwrite parts of memory with exploit code.

The easy safe solution is to use calloc() which will detect the overflow (at least on most common libc implementations). If you really need to use malloc() for some reason, you can check for overflow separately.


The code starts off very well, with a check to make sure there are not too many arguments, but it doesn't do enough error checking. There could be too few arguments as well (no file name on the command line). Errors in the execution of the file should return a non-zero number and zero for success. Try using the constants EXIT_SUCCESS and EXIT_FAILURE that are defined in stdlib.h. There probably should be an error check to see if fopen() returns a valid file pointer or not.

Generally in C variables are named in lower case, constants and macros are named in all upper case. The constant MAX_ARG follows this standard, but the variables LINE_COUNT, FNAME, FILE_LENGTH and CHR are all opposite to the standard.

The function fgets() would be very useful to the program, and possibly enhance performance. fgets() retrieves a line of text from a file if the buffer supplied is big enough.

You could also input a sector at a time as @Maybe_Factor suggests, although it would probably be better to start testing with 4K, then 8K and up to 64K based on the operating systems blocking factor.


Streams clean this up a little bit, however I removed print statements here so that the logic can be seen a little clearer:

String code = "53492";
int guesses = 10;
Scanner scanner = new Scanner(System.in);

while (guesses-- > 0) {
    String guess = scanner.nextLine();
    if (guess.equals(code)) {
        return; //guess was correct, can also just compare correct to guess length
    }

    int correct = compare(guess, code, Stream::count); //count elems
    int combo = compare(guess, code, s -> s.reduce(0, Integer::sum)); //sum
    // print information, note this requires three iterations since we stream twice
    // and have an #equals check. There are still some optimizations you
    // can make to remove this
}

//elsewheres
public <R> R compare(String one, String two, Function<IntStream, R> back) {
    //apply our stream function to an intstream for a mutable return
    return back.apply(IntStream.range(0, code.length())
                      .filter(i -> guess.charAt(i) == code.charAt(i)) //correct chars
                      .map(i -> guess.charAt(i) - '0')); //map to values
}

It seemed like it would be a neater solution before I actually sat and wrote it, but I figured it'd be nice to at least see an alternative.


How to append values into existed Vec with iterator

I have got an answer with chain
fn main() {
    let mut scan = Scanner::default();
    let n: usize = scan.next();
    let mut arr = vec![0];
    let mut arr: Vec<i32> = arr.into_iter().chain((0..n).map(|i| scan.next())).collect();
    println!("{:?}", arr);
}


you can replace if is_complete == true with if is_complete
the only thing that changes is :conditions, tasks = ... should not be inside the if/else
the 3rd case is invalid: completed_date can't be NULL and within a certain range at the same time
use one conditional for the NOT in completed_date IS (NOT) NULL and one for the and DATE ..., and concatenate the sql string then. Then the nested if/else is gone.
the extra query arguments start_date and end_date depend only on start_date && end_date, so the distinctions should not be in the is_completed conditional.


Node module using promises and the revealing module pattern

Overall it looks pretty good, but I do have some notes:

You export new Foo but your Foo function isn't really a constructor. It's just a function that returns an object. This works just fine (one of JS' oddities), but personally I'd just call the function foo - lowercase, not a constructor - and use module.exports = foo();.
You're skipping most semicolons - and you're skipping them inconsistently. Even if it was super consistent, I'd still give you my standard "I prefer to add semicolons myself, rather than let JS 'fix' my code"-speech, but since it's inconsistent that goes double. It's one thing to insist on skipping semis, it's another to kinda, sorta mostly skip them.

My usual speech is that since semicolons are required in some places, and since JS does semicolon insertion, then JS actually needs those semicolons. It's not that they're optional, it's that JS is trying to make sense of incomplete code. Personally, I'd just rather just write complete code.
I'd probably prefer to tell the module where to store its "foo.json" file. From the outside, there's no indication of how it's caching things - much less that it (over)writes a file in the working directory. That's a nasty surprise.
You could simply export your Foo pseudo-constructor function (rather than its return value), and then give it a path argument when creating it.

foo = require("foo")("/path/to/some/dir"); // or a path to a specific file

I'm on the fence about the emptyJSON thing. It's not really empty: There's a structure there. This implies that some other code of yours expects that structure to be there instead of doing proper error handling. But that's not your module's problem. I'd rather forward any errors.

On the other hand, you've hard coded the URL to fetch, so your code already has some major external coupling. As long as that URL's there, it's not a big deal to also hard code a blank response - but should that URL actually be there? Depends on how generic you want this to be. You current code is almost perfectly generic in the sense that it could fetch and cache any given JSON document, so I'd be tempted to make the URL an argument to. But it would also necessitate that you remove emptyJSON and forward errors, since you no longer know what even an "empty" response looks like.
Your flow is a little odd: saveJSON resolves its promise using cachedJSON. This means that you're first serializing the JSON, writing a file, then reading the file and deserializing the JSON, even though you have all of it in memory when you call saveJSON. It's just a very roundabout way of doing things. By the way, the json variable seems pointless.
Most of all, I'd like a function that returns JSON whether or not it's cached. Especially since you "hide" errors by returning JSON in all cases. That basically means that if I call cachedJSON and there isn't any cache, I still get a JSON object. An object I'll have to dig into to figure out if it actually contains anything (which implies I know what to look for etc.). And even so, I don't know if it's "empty" because there's no cache yet, or because the request failed, or because the JSON was invalid. I'm completely in the dark.

So I basically have to call refreshJSON exclusively. I'd always have to call it at least once to ensure that something's been cached. But a CLI script doesn't have an easy way of know if it's running for the first time (and needs to refresh) or the 234th time (and can try the cache). So net result is that I'm better off always calling refreshJSON and never bother with cachedJSON at all. Which, in turn, makes it all kinda pointless - you just give the the hard disk some unnecessary exercise (doubly so with the write-then-read thing).

A caching proxy like this should primarily be transparent, with the option of going straight for the cache (and perhaps getting null or undefined back), or forcibly refreshing the cache, even if it exists. Of course, here it gets kinda tricky, since one of the 2 hard problems in programming is knowing when to invalidate your cache. Thankfully files are timestamped, so you could just use that plus a max age value to know if and when you'd need to refresh the cache. The max age could be (yet another, but optional) argument to the exported function.

Basically, I'd like to use the module like this:

var cache = require('foo')('/some/path/to/use', 'http://example.com/index.json', 3600);

// just give me the JSON; I don't care if it's cached or not
cache.getJSON().then(function (json) {
  // yay, data.
}).catch(function (err) {
  // handle errors here
});

That's of course presuming a very generic implementation. You could also just hard code the URL, file path, and max age - but your code wouldn't be very reusable. But that's fair too, of course. Depends on your needs.

As a side-note: You say your module is "similar to this". The code itself looks pretty complete, so I can't imagine what you're left out. But whatever's been left out, I obviously can't review (nor can anyone else). Hence the rule that  questions must contain the real code to be on-topic for Code Review. As mentioned, your code looks pretty close to complete, so it's fine to review. But then wouldn't it have been easier to actually post the real code?


I'm commenting on the edited version only. It's fine, but

char cur = s.charAt(0);

throws for the empty string. You could special case it, but in general, it's better to do it the other way: Maintain a state containing a lastCharacter and a count. The initial state has count=0 (lastCharacter is initially arbitrary).

StringBuilder result = new StringBuilder();

You could pre-size it using s.length as it's a sure upper bound. Not very important except maybe for long strings.

 result.append(cur);

Your approach needs this action at the beginning, while mine needs it at the end. You need also a complicated condition like if((i == s.length() - 1) && (count > 1)) which I don't want to understand.

for(int i=1; i<s.length(); i++) {
  char nxt = s.charAt(i);

Saving a single character compared to next is not worth it, is it?

You should also fix your spacing, especially add a space after for and if. Use your IDE.

I'd propose something like (my spacing is not conform, please ignore)

private static String compressString(String s) {
    StringBuilder result = new StringBuilder();
    int count = 0;
    char last = ' '; // doesn't matter
    for (int i=0; i<s.length(); i++) {
        char c = s.charAt(i);
        if (count==0) {
            last = c;
            count = 1;
        } else if (c==last) {
            count++;
        } else if (count==1) {
            // While this ensures the string never grows,
            // it also creates the ambiguity mentioned below.
            result.append(last);
            last = c;
        } else {
            result.append(last).append(count);
            last = c;
            count = 1;
        }
    }
    if (count>0) {
        result.append(last).append(count);
    }
    return result.toString();
}

Note that whenever the string contains digits, it gets irreversibly mangled:

`11` -> `12`
`12` -> `12`


Some thoughts:

You are using async but not "using" it.  You can simplify this code for the reader by doing const accessToken = await axios.post(...); and similar to de-nest and make the code more understandable. This also helps your avoid bad variable names like res1, res2, res3, etc.
Promise.all() is your friend when it comes to making batch calls like this.  Combined with a tool like your waitFor function, you can introduce any kind of request pattern you want.  Right now you are making calls in series which is kind of harder to throttle when it comes to meeting rate limits, as now you have to account for response times in determining when to make next call vs. an up-front staggered triggering of the requests that can be possible with Promise.all() (see example below).
If you are going to use a tool like axios or Fetch API that require a res.data or res.json() type of step, you might consider putting a simple wrapper around the response handling to clean up code a bit. This is also a good way to standardize error handling at the client level. In this case, I think such a wrapper could also be used to manage the access token state (though not shown that way in my example below).
Break down your code along logical functional lines (another option available to you after using async more conventionally).  For example, the status request and strapi update are one logical operational unit.  Getting the server list is another logical piece of functionality.
If you control your strapi endpoint/database you should consider adding/leveraging bulk query support for the datapoint updates. Querying in loops is kind of an anti-pattern and pretty much any modern data store supports bulk updates.
I would recommend defining key constants/variables for aiding in code understanding and maintenance. For example, if I wanted to migrate to v2 of this API at some point, I don't want to have to go replace v1 with v2 in a bunch of places.  Centralize how you hold such module "configuration" logic. This makes your code's dependencies much more visible. For example, defining apiKey and email from process.env in my example below makes it really clear to the reader that this dependency exists, without having to find the variable mixed into a string definition deep down in the code somewhere.
Consider implementing more appropriate error handling. My guess is that this server monitoring process shouldn't be designed to just silently swallow errors.

Putting it together might yield something like:
import axios from 'axios';
import strapi from 'your-strapi-module';

const apiBase = `https://api.cloudways.com/api/v1`;
const apiKey = process.env.CLOUDWAYS_API;
const email = process.env.CLOUDWAYS_EMAIL;
const maxRps = 10; // max requests per second for throttling
const throttleInterval = 1000 / maxRps;

// a small wrapper around axios for this particular API
// this might best live in a separate module
const apiRequest = async ({ headers = {}, method = 'get', url }) => {
  const opts = {
    baseUrl: apiBase,
    headers,
    method,
    url
  };
  return axios(opts).then( (res) => res.data );
};

// method to obtain OAuth token, again perhaps best in separate module with API axios wrapper.
// this could be made to lazily provision the token on any API request if not already received
const getAccessToken = async () => {
  const method = 'post';
  const url = `/oauth/access_token?email=${ email }&api_key=${ apiKey }`;

  const data = await apiRequest({ method, url});
  return data.access_token;
};

const getServerList = async () => strapi.query('server').find({});

const wait = (ms) => new Promise( (resolve) => setTimeout(resolve, ms) );

const updateServerStatus = async (serverId, accessToken) => {
  const url = `/server/monitor/summary?server_id=${ serverId }&type=db`;
  const headers = {
    Authorization: 'Bearer ' + accessToken
  };

  return apiRequest({ headers, url })
    .then( ({ content }) => {
      // I am not throttling here as no need to throttle this data store query was noted
      // Ideally, this could be made into single update query though
      const promises = content.map( (app) => {
        return strapi.query('subscription').update(
          { ApplicationSlug: app.name },
          { DiskUsage: Math.ceil(app.datapoint[0]) }
        );
      });

      return Promise.all(promises);
    });
};

const updateAll = async () = {
  // we can parallelize getting access token and getting server list
  const initPromises = [
    getServerList(),
    getAccessToken()
  ];

  const [ serverList, accessToken ] = await Promise.all(initPromises);

  // map your server list to an array of update promises
  const updatePromises = serverList.map((server, i) => {
    // stagger the requests to meet rate limits
    return wait(i * throttleInterval)
      .then( () => updateServerStatus(server.ServerId, accessToken) );
  });

  return Promise.all(updatePromises);
};

// call the main function somehow (could be exported from module for example)
export {
  updateAll as default,
  updateAll,
  // again, following probably make sense in separate module
  apiRequest,
  getAccessToken
}

Note that since we are now "using" async in a more appropriate fashion you now begin to make your logic available in specific functions.  For example, if I just wanted to allow one to update the status of a single server, I could expose the updateServerStatus function in exports. There would have been no way to offer that sort of code flexibility with your current approach of using nested thenables.


Two classes to avoid confusion when handling degrees and radians

Design

While it might seem that the current design is working fine, I think there are two distinct issues lurking beneath the surface.

Issue #1: operator double

From what I can tell, the intention behind these unit classes seems to be the prevention of unit mismatches. Providing an access function to the contained value is not a bad idea, but using the implicit conversion operator for doing so is probably not the wisest choice here.

Consider the following snippet:

auto angle = Degrees{ 180.0 };
auto sine = std::sin(angle);

It compiles easy enough, but will then fail silently at runtime. It likely won't even crash the application, but quietly produce values different to those expected.

Of course, this is a contrived case ("std::sin is not really in the scope of this library (yet)!"), but nonetheless it shows a problem: As it is, there is hardly any prevention of accidental unit mismatches.

Adding the keyword explicit to operator double() might help with some of these cases (though not with std::sin), but not all of them.

  If this were the only issue, it would be easy to fix with a getter function with a descriptive name (e.g. getDegrees).

Issue #2: Extensibility

Let's say that in the future, you (as the library developer) want to add another representation for angles (e.g. gons/gradians). Sounds simple, right?

And at that point, it is. Adding one more class according to the given scheme, four more converting constructors, and it is done.

  Someone familiar with the SOLID principles might already spot a code smell in the last sentence: four more converting constructors, two of which have to be added to the existing and otherwise rather independent classes Degrees and Radians, thus violating the Open-Closed part of SOLID.

After that comes another user A of the library and wants to add his own custom angle representation RepA. And then comes user B with RepB.

And suddenly, we're having twenty converting constructors just for those five classes. And each additional representation is going to add a lot more: For \$N\$ representations, we need \$N \cdot (N - 1)\$ converting constructors to cover all combinations.

  And that is assuming independent developers add converting constructors for each others implementation. Otherwise, operator double will again lurk in the shadows, allowing for code to compile that really should not.

class Gradians {
public:
    Gradians(double);
    Gradians(const Degrees&);
    Gradians(const Radians&);
    operator double() const;
    // ...
};

class Turns {
public:
    Turns(double);
    Turns(const Degrees&);
    Turns(const Radians&);
    operator double() const;
    // ...
};

  Now stuff like auto a = Gons(300.0); auto b = Turns(a); will actually compile, but produce wrong results (b == 300.0 instead of b == 0.75).

How can we solve this conundrum?

A first step would be to separate the value from its representation(s) by choosing one internal representation which can be converted on demand:

class Angle {
public:
    static Angle fromDegrees(double degrees);
    static Angle fromRadians(double radians);

    double radians() const;
    double degrees() const;
private:
    Angle(double radians) : radians_{ radians } {}

    double radians_;
};

Angle Angle::fromDegrees(double degrees) {
    auto radians = degrees * SoC::Maths::Trigonometry::DegToRad;
    return Angle{ radians };
}

Angle Angle::fromRadians(double radians) {
    return Angle{ radians };
}

double Angle::degrees() const {
    return radians_ * SoC::Maths::Trigonometry::RadToDeg;
}

double Angle::radians() const {
    return radians_;
}

As you can see, I chose radians for my internal representation (mostly because that's what the trigonometric functions of the standard libary expect). For adding a new representation, we now only need to add one factory function (fromXyz(...)) and one getter function (xyz()).

  While this is a lot cleaner (and takes care of some issues), SOLID devotees will not fail to notice that the violation of the Open-Closed principle hasn't been fixed yet, just moved.

  To address this, we could introduce a hierarchy of derived classes, but that seems like overkill for this problem.

  Another easy solution would be to use templates:

struct Degrees {
    static double toRadians(double degrees) {
        return degrees * SoC::Maths::Trigonometry::DegToRad;
    }
    static double fromRadians(double radians) {
        return radians * SoC::Maths::Trigonometry::RadToDeg;
    }
};

struct Radians {
    static double toRadians(double radians) { return radians; }
    static double fromRadians(double radians) { return radians; }
};

class Angle {
public:
    template<typename Representation>
    static Angle from(double value) {
        return Angle{ Representation::toRadian(value) };
    }

    template<typename Representation>
    double as() const {
        return Repreentation::fromRadians(radians_);
    }

private:
    Angle(double radians) : radians_{ radians } {}

    double radians_;
};

 // Usage
 auto angle = Angle::from<Degrees>(180.0);
 auto sine = std::sin(angle.as<Radians>());

Of course, this is far from done, yet:

Operators for addition, subtraction (angles), multiplication and/or division (scalars) could be overloaded for this Angle class
For demonstration purposes I didn't mark the member functions above noexcept or constexpr. This should likely be amended.
Helper functions like sin, cos, tan and similar could be provided for this Angle class.
For the template version: The templates could be restricted to only accept types with correct signatures for fromRadians and toRadians.

Implementation

Aside from the design considerations mentioned above, I can add these points for the general implementation:

Consider marking converting constructors and conversion operators as explicit.
Very likely sizeof(Degree) == sizeof(double), so there probable won't be a benefit for taking a const Degree& parameter over just Degree.
I'd suggest checking the precision of the constants ' DegToRadandRadToDeg`, especially if calculated on your own. If the precision on these constants is poor, there might be small numeric errors that accumulate over multiple conversions to and fro.
A comment reads /// Function Call Operator: Actually, no, this is a conversion operator. A function call operator would look like this: double operator()() const.
Generally, the comments don't tell me much about anything. Unless there is a hard requirement for them (in which case they should be improved) I'd suggest removing them. In their current form, they are at best visual clutter, and confusing at worst.


Bug in Solution3  (using heapq)

The items being put on the heap need to be fully sortable.  Tuples are compared element by element. If the first element of two tuples compare equal, then the next element of the two tuples are compared.  In your solution, the second element of the tuple is a ListNode.  But no methods for comparing ListNodes have been defined.  So if the first element of the tuples are equal a TypeError will be raised when the ListNodes are compared.  The solution is to use 3-tuples: (value, seq_no, ListNode), in which the seq_nos are unique.

class Solution3:
    # @param a list of ListNode
    # @return a ListNode
    def mergeKLists(self, lists):
        dummy = ListNode(0)
        current = dummy

        heap = []
        for seq_no, sorted_list in enumerate(lists):
            if sorted_list:
                heapq.heappush(heap, (sorted_list.val, seq_no, sorted_list))

        while heap:
            _, seq_no, smallest = heapq.heappop(heap)
            current.next = smallest
            current = current.next
            if smallest.next:
                heapq.heappush(heap, (smallest.next.val, seq_no, smallest.next))

        return dummy.next

See discussion in heapq documentation: https://docs.python.org/3.7/library/heapq.html#priority-queue-implementation-notes


WebAPI - Return models vs entity and partial class with meta data

No matter how simple I think my application is going to be, I always end up separating my viewmodels from my entities. Not only do I always encounter at least one case where the apparent convenience of any other approach makes it very unwieldly for me to finish a feature, but it's also good to practice loose coupling between your views and your domain.

Say you're using entities with partial classes directly in your views, and the same entity is used in multiple views. Now you have a new feature that requires a change to your entities. How do you know it won't break your existing views? The compiler won't catch it, unless you have an automated suite of UI tests, you'll need to remember to manually test every screen again.

Instead, if you create one viewmodel per view, you get the following advantages:

Each viewmodel can be constructed to meet the needs of a single view. Don't need to some properties of an entity? Leave it out of the viewmodel! Want to include a few extra properties? Throw them in! Want to flatten out some entity hierarchy because it will be easier to display? Do it!
Some (but not all) breaking changes you make to your entities will now be detected by your compiler. Even if you have unit tests (and you should), this is a nice reminder.
Factories are much easier to test than views.

In summary, the viewmodel should be the simplest representation of what the view needs, and no more. This decouples your entities from your views as well as decouples your views from each other. It also places mode code where it can be easily tested and maintained. It is a little more work initially but a lot less work in the long run.


Checking for one- or two-dimensional palindrome strings

I made some changes, not sure this is better though. It is all a matter of opinion. This is not intended to be "the" answer.

I however find this quite interesting. The goal in my opinion should always be to write "easy-to-read" code.

i = input("Please enter a phrase to check if it is palindrome: ")
s = str(i).upper() #transform the string to uppercase
l = s.split()

num_words = len(l)
print ('The string to check is: \"{}" and has {} words'.format(s, num_words))

# Variables to test
two_d_palindrome = False
one_d_palindrome = False

# reverse lists
rev_l = list(map(lambda x:x[::-1], l[::-1]))

#two-dimension palindrome check - with two full lists
if l == rev_l:
    two_d_palindrome = True
    print ("The string %s is a two-dimension palindrome" % s)

#one-dimension palindrome check
else:
    s = "".join(l) #string without spaces
    if s== s[::-1]:
        one_d_palindrome = True
        print ('%s is a one-dimension palindrome' % s)

#no match
if not (two_d_palindrome or one_d_palindrome):
    print ("Your string is not a palindrome")


Is there a better flow for returning the response?

I think this generally looks pretty good.  I would consider two things:

First I don't like the "internal" option here which leads to mixed return values.  Have you considered having getSessionNameSpaceInternal() which would call this method and extract the desired return value from the JsonResponse?
Doing the above would allow you to directly return from catch block s like this:

} catch (ClientException $e) {
    return new JsonResponse(
        'The endpoint responded with a ' . $e->getCode(),
        $e->getCode()
    );
} catch (\Exception $e) {
    return new JsonResponse( $e->getMessage(), $e->getStatusCode() );
}


You can simplify the loop in main. flag is unnecessary. Just use an infinite loop with a break statement. Also, because you know that any number with a zero as the last digit won't be a palindrome, you can skip those.
Putting those together, you get:
for (;;) {
    reversenum = reverse_num(n);
    if (reversenum == n) break;
    ++n;
    if (n % 10 == 0) ++n;
}

This will skip about 10% of the possible candidates.
An additional possible improvement (which is left as an exercise for the reader) involves determining what the largest digit of n is, then only looking at numbers that have a last digit that matches. This would allow you to skip 90% of the possible candidates with little additional overhead.


General Comments

mkEdges

I would probably just call this function edges.  mk (which I assume is short for make) has an imperative ring to it.

bfsPathLength :: Int -> Index -> [State] -> Int

You are forcing users of bfsPathLength to pass an initial state.  This forces them to be aware of the internal details of the algorithm, which is not a good design.  You could get rid of the [State] parameter and have bfsPathLength delegate to a helper function that takes the initial state.  Public interfaces should never expose details that aren't necessary.

bfsReachableLocations :: Int -> [(Int, Index)] -> [Index] -> Int

What's the purpose of this function?  It doesn't appear to be used for computation of the actual answer to the riddle.  If it's for debugging purposes, you should add a comment that says so (be sure to include what it actually does, and why it's useful for debugging as well).
Also, once again you force users to incorporate knowledge about the internal state of the algorithm.

Performance

You perform a linear search for nodes in the queue and the visited set.  You should use a more appropriate datastructure, such as a set, that can do the search in \$O(\log{n})\$, or even \$O(1)\$, time.

Abstraction

Consider separating the graph generation from the search algorithm.  This will allow you to use BFS search to solve other problems.  You have some options here, including:

Turn mkEdges into a parameter to the search function.
Use a typeclass.

For example, if you turn mkEdges into a parameter (and remove the internal state parameter), bfsPathLength might have the following type signature:

bfsPathLength :: (a -> [a]) -> a -> Int
bfsPathLength edgeGenerator goalLocation = ...

You should parameterize the start location:

bfsPathLength :: (a -> [a]) -> a -> a -> Int
bfsPathLength edgeGnerator startLocation goalLocation = ...

It seems like it would be useful to be able to find the actual path in most cases, rather than just the length:

bfsPath :: (a -> [a]) -> a -> [a]

Then you can write bfsPathLength as follows:

bfsPathLength :: (a -> [a]) -> a -> a-> Int
bfsPathLength edgeGenerator startLocation = length . (bfsPath edgeGenerator startLocation)


PHP function (in WordPress) echoing HTML

There are several issues I have with your function. Some are about your function breaking the basics about what a function is/should do, others are perhaps a tad more personal (as in: a matter of personal preference).

Functions do stuff, without it impacting the rest of the code

It seems almost silly to explicitly state this, but let me explain what I mean. A function is a unit of code, that performs a single task, that might be required to be performed several times. Functions should not have "side-effects". That's a fancy way of saying that calling a function shouldn't disrupt the rest of the code (with the exception of a function throwing an Exception, of course).

Your function, however, generates output without the caller having any means of controlling what, how and to where that output is being sent. The function assumes the caller knows that it'll send output, but that's a rather dangerous assumption to make. A simple example: cookies can't be set after any output has been sent already. Therefore:

my_html_function();
set_cookie();//<-- FAILS!

The function contains an echo, and so output will be sent once a call is made. It might seem like an obvious thing to fix, but in larger projects, things like this can really trip you up, and you'll find yourself wasting hours trying to work out why the cookie isn't being set properly.

Bottom line: Functions return, they don't echo, so change the echo in your function with return, and echo in the template.

PHP stands for PHP: Hypertext Preprocessor

The important bit in this case is Preprocessor. You can use PHP to return/echo strings of markup, but why would you do that? You can embed PHP in HTML just as easily, so why not use that? If needs must, you can always use PHP to include bits and pieces of markup.

Markup isn't static

Sure, the markup your function echoes/returns is static in your case, but markup languages are, well, languages. They're not always static. It's not a big stretch to imagine a situation where you want your function to churn out a block of markup where the title value is different, or the number of list items is variable.
In those cases, you'll want to pass arguments to your function, and you'll find yourself generating markup dynamically. It's not a hard thing to do, and it's done all the time.

To this end, you have a number of options available to you. The easiest (and in this case reasonable) approach would be to string together the markup:

/**
 * ADD THIS, DOCUMENT YOUR CODE:
 * Pass the title string and an associative array of list items
 * @param string $title
 * @param array $listItems
 * @return string
 */
function getTitleList($title, array $listItems)
{
    $title = sprintf('
%s
', htmlentities($title));//<-- sanitize $title, it shouldn't contain markup
    $liNodes = [];//array of li nodes
    //again, we need to sanitize all this
    foreach ($listItems as $id => $value) {
        $liNodes[] = sprintf(
            '
%s
',
            str_replace('"', '\'', $id),//we're using "as id delimiter, so id can't use them
            htmlentities($value)//html entities must be removed
        );
    }
    $markup = $title . '
' . implode('', $liNodes) . '
';
    return $markup;
}

The alternative here would be to use an actual DOM parser/builder, like the DOMDocument class, although in this case, that would be overkill IMO. As @KIKOSoftware said: sprintf is marginally slower than regular concatenation, and it could be said that it's a bit harder to use at first. If you want, you can use regular concatenation just as easily:

$title = '
' . htmlentities($title) . '
';//same as sprintf above

Another thing that was pointed out to me in the comments was that, if the contents of any of your tags contains markup, then obviously htmlentities is not what you want to use. If you require your function to be flexible (and allow the insertion of nested tags), you should really look into using an actual DOMDocument-like tool. Something that enables you to build the DOM as you go (creating new nodes, setting attributes and inserting them throughout the actual DOM tree).


Warning: The following is opinionated at times. At other times it is more opinionated.
Channeling PG
I've heard on the internet so it must be true, that Paul Graham will get right to the point when interviewing applicants to Y-Combinator with "What problem does this solve?" It's hard to understand code without understanding what it is supposed to do. And only Google and watching a video twice make me think I might. Since I still don't understand the code though, I can't tell whether it solves the problem or not.
The "water pouring problem" is a canonical toy problem in programming curricula. Wolfram Mathworld describes it as a special case of the three jugs problem. The special case is where the third jug:
   capacity = +infinity
   contents = +infinity

The infinite capacity of the third jug allows it to represent a sink into which the contents of the other jugs may be emptied. The infinite contents allows the third jug to represent a faucet for filling other jugs.
The problem Ordersky presents is none of these. It is a generalized case based on a Python example from Peter Norvig's Design of Computer Programs course at Udacity. The problem Odersky is solving has an arbitrary number of jugs with finite capacity plus one jug with infinite capacity and contents. I would like to dub this the "n+1 Jugs Problem" because 1 captures the sink/faucet and n+1 hints at the notion of +infinity [at least in my little world].
Readability
A joke: I married my wife despite her adamant unwillingness to change her name. What's the big deal about being called "Donna" to match my tattoo?
Rich Hickey invented Clojure to help working programmers write good programs, not to give the world another excuse for tribal tattoos. I don't think init or def inside a function are big deals. They're very Pythonic and they couldn't make the code less readable for idiots like me.
Chiapas
I found the code opaque. "What is state?" I asked myself. I could look at the code for hours and never really figure it out. It took a half hour of concerted effort involving Google and watching a video of Martin Odersky...twice before I came up with a good answer: state is a vector of integers. In Ordersky's code this is explicit at line 6:
 type State = Vector[Int]

That's just standard Scala. It's fast in the sense that many people will understand it as soon as they read it. The Clojure implementation, on the other hand, is really slow because the source code doesn't make the nature of state clear. A [more opinionated][more opinionated] approach might be:
 ;;;; The state is a vector of integers.
 ;;;; Each element represents a glass.
 ;;;; The value of each element represents the contents of the glass.

A more direct implementation of the Scala code might use int-array for both state and glasses. There's nothing wrong with using types to make writing correct clear performant code easier.
Recommendations
Think about how much effort Odersky invests in making his code understandable. There's thirty minutes of video. There's the hours of video that come before it in the course sequence. The coding session starts with diagrams explaining the problem. Those are habits that are worth emulating. Following what Clojurists on the internet espouse doesn't make one an expert [I am aware of the irony]. Clojure is the product of Hammock Driven Development.
Extension
I'm a big fan of Lamport's idea specification as the starting point. One of the issues with Odersky's generalized approach is that it doesn't quickly trim the search space. Consider the case with two glasses:
 (def capacity  { :a 1
                  :b 100})
 (def target  50)           ; edit: early version used 99

The solution exists in the 99th layer of Odersky's onion because it requires 99 moves. With two glasses There are only six transition operations at each level of the onion:
 ; empty a
 ; empty b
 ; pour from a to b
 ; pour from b to a
 ; fill a
 ; fil  b

Yet the brute force search would cover:
 level | paths
 ------|-------
 1     |  2
 2     |  12
 3     |  72
 4     |  432
 ...   |  ...
 99    |  3.6295479083337274E76 = (6^99)/3

At an arbitrary iteration some may lead to states already visited and Odersky's approach trims those. What it doesn't do is capture the semantics of bags to trim the search space. Consider:
 (def capacity  { :a 1
                  :b 100
                  :c 1
                  :d 1
                  :e 1
                  :f 1})
 (def target  50)           ; edit: early version used 99

Many of the (Math/pow 42 99) states turn out to be equivalent and finding these equivalences would greatly reduce the search space and make for a more performant algorithm. For the purposes of Odersky's course [promoting Scala and functional programming] looking at algorithmic improvements is outside the mandate. For general code such as that under open review, it really isn't.


Glad you're taking on Java!

You should study Object Oriented Programming (OOP), which is core in Java, a little bit more to use classes in a more suitable and efficient way.

The general rule of a class is "one class one purpose" which it looks like you're trying to apply, but since you don't have any objects, it becomes a bit arbitrary.

An example would be to have a class called Calcualtor that has functions for what a calculator could do, then you could have another class called InputHandler that handles the reading from the user interface (in this case that's the terminal). It's very bad to call the Main class in all classes, it's very backwards, main is supposed to handle the other classes and there's only one Main.

Because of the structure you have here you notice that you find yourself using static a lot, we call this "static overuse". If you apply OOP properly you won't need static unless there's an intended use, like a variable that never changes and is the same for all objects of that type.

You should be fine by just rearranging your methods into objects and call them from main:

public class Main {
    public static void main(String[] args) {
        InputHandler inputHandler = new InputHandler();
        inputHandler.start();
    }
}

Input Handler:

public class InputHandler {
    /* Notice how I put the calculator and scanner up in the
       object-scope, you can now re-use them throughout this object.
    */
    private Calculator calculator = new Calculator();
    private Scanner sc = new Scanner(System.in);
    private boolean keepOn = true;

    public void start() {
        System.out.println("Welcome to my calculator!");
        performAction(1);  // This is what we call a magic number. Don't do this, instead you could make variables for the options, or, you could make an enum.
        while(keepOn == true) {
            calculate();
        }
    }

    public void calculate() {
       int action = selectAction();
       performAction(action);
    }

    public double getFirstNumber() {
        System.out.println("Input the 1st number");
        return sc.nextDouble();
    }

    public double getSecondNumber() {
        System.out.println("Input the 2nd number");
        return sc.nextDouble();
    }

    public char chooseOperator() {
        System.out.println("What to do?" +
                "\n + for add" +
                "\n - for minus" +
                "\n * for multiply" +
                "\n / for divide" +
                "\n % for mod" +
                "\n ^ for first number into the power of second number");

        String operator = sc.next();
        return operator.charAt(0);
    }

    public int selectAction() {
        System.out.println("Dormammu, I came to bargain! " +
                "Wanna do some extra calculations?" +
                "\n 1 - for 'Yes'" +
                "\n 2 - for 'No'");
        int dormammu = sc.nextInt();
        return dormammu;
    }

    public double performCalculation() {
        char operand = chooseOperator();
        double firstNumber = getFirstNumber();
        double secondNumber = getSecondNumber();
        double result = calculator.calculate(firstNumber, secondNumber, operand);
        System.out.println("The result of " + firstNumber + operand + secondNumber + "is: " + result);
        return result;
    }

    public void performAction(int action) {
        switch (action) {
            case 1:
                performCalculation();
                break;
            case 2:
                System.out.println("Okay! Nobody misses you" +
                        "\n But here's the calculations you've done so far");
                for (int i = 0; i < calculator.calculations.size(); i++) {
                    System.out.println(calculator.calculations.get(i));
                }
                keepOn = false;
                break;
            default:
                System.out.println("Shit, wrong answer, try again!");
                calculate();
        }
    }
}

And the calculator:

public class Calculator {
    public Vector<Double> calculations = new Vector<>();

    public double calculate(double firstNumber, double secondNumber, char operand) {
        switch (operand) {
            case '+':
                calculations.addElement((firstNumber + secondNumber));
                return firstNumber + secondNumber;
            case '-':
                calculations.addElement((firstNumber - secondNumber));
                return firstNumber - secondNumber;
            case '*':
                calculations.addElement((firstNumber * secondNumber));
                return firstNumber * secondNumber;
            case '/':
                calculations.addElement((firstNumber / secondNumber));
                return firstNumber / secondNumber;
            case '%':
                calculations.addElement((firstNumber % secondNumber));
                return firstNumber % secondNumber;
            case '^':
                calculations.addElement(Math.pow(firstNumber, secondNumber));
                return Math.pow(firstNumber, secondNumber);
            default:
                System.out.println("Oops! Received an operand that's not supported! How'd that happen?");
                throw new UnsupportedOperationException();
        }
    }
}

This is just a small refactoring of your code. You should always treat user input with great care and use try-catch to make sure the input is what you expect. Your application will crash if you type no instead of 2.

Also notice how I used some recursion in performAction(int action) where if you do not get the expected answer it re-attempts to do the calculation. This however only works if the other answer is a digit. I'd recommend you try to read a String and then try to convert it to an int using Integer.valueOf("1") and catch errors if it's not a number.


Giving multiple choices that lead to different scenarios

Style:
Avoid multiple statements in one line, as you did here:

say(event[8]); say(event[9]);

Variable naming:

String[] event = ...;

It would be better to name the array events or eventArray, as you are storing multiple events.

int[] statsChanged = new int[] {0, 0, 0, 0};

statsChanged sounds like you only have true or false options, however you are assigning integer values to the elements, which have more than two options. Therefore a name such as statsLevels would be more appropriate.

Iterating through an array. Instead of:

int i;
for (i = 0; i < 7; i++) {
    say(event[i]);
    next();
}

do

for (String e:event) {
    say(event);
    next();
}


My answer is going to focus on your use of shell functions and global variables.  There aren't any actual syntax errors in your script AFAICT, but your misuse of functions in this script is dangerously error-prone.

There are two main reasons for using a function in bash (or any language, really).

The first is to parameterise a frequently performed operation - e.g. by passing arguments to it rather than hard-coding values (or relying on side-effects).  Optionally it should return a result to the caller (in shell, by printing something to stdout to be captured with command substitution.  Or sometimes by changing a variable in the environment - but see below about that)

You're not doing that.

Worse, you're making your functions rely on global variables.  This makes your functions (and your scripts) dependent on side-effects of previous variable definitions - which may still hold old values from previous runs (and you forgot to update them for the current run) or, worse, may be empty because they haven't been initialised yet in the current shell.  This will inevitably lead to catastrophic data-loss one day when you forget to set a value for "$drt" and/or "$domain" and/or your many other global variables.

Better to pass values as parameters when and as needed. Don't trust that a crucial variable happened to have been set some time in the past - i.e. be explicit, not implicit.

As a rule, functions should be self-contained and not rely on variables that may or may not be defined outside of their scope.  They should also define variables as being local to them so that they explicitly don't use (or worse, change) a global variable that happens to have the same name as the function's variable.

Anyway, an example of how your wordpress function could be written:

wordpress() {
    local drt="$1"
    local domain="$2"
    local dbpass="$3"

    # should do more checking here, this is the bare minimum.
    # it avoids running `rm -rf /` if both $drt and $domain
    # are empty, and running `rm -rf "$drt/"` if $domain is empty.
    [ -z "$drt"    ] && error 1 '$drt is empty. aborting!'
    [ -z "$domain" ] && error 1 '$domain is empty. aborting!'
    [ -z "$dbpass" ] && error 1 '$dbpass is empty. aborting!'

    # should check exit status of each command run here and take
    # appropriate action on any failures.  Figure out what you want
    # to happen if any of the following fail and implement it.
    rm -rf "$drt"/"$domain"/ 2>/dev/null
    wp core download --path="$drt"/"$domain"/ --allow-root
    wp config create --path="$drt"/"$domain"/ --dbname="$domain" \
      --dbuser="$domain" --dbpass="$dbpass" --dbhost=localhost \
      --allow-root
}

You'd call it as wordpress "$drt" "$domain" "$dbpass".  It uses a function called error:

error() {
  local ec msg

  ec="$1" ; shift
  msg="$*"

  [ -n "$msg" ] && echo "$msg" >&2
  # don't exit if $ec==0 - just return after printing a warning to stderr
  [ "$ec" != 0 ] && exit "$ec"
}

The second reason is to make the structure of the script easier to follow.  For example, instead of having a lot of shell code for each pattern matched in a case statement (which makes it difficult to see at a glance what the cases are and what each one does), write a function for each case and call it - with or without arguments.

You're not doing that either - you're using each function as soon as you define it.  That's both weird and pointless....especially so since your functions don't take arguments.

A more usual way of defining and using functions would be something like:

function1 () { ... ; }
function2 () { ... ; }
function3 () { ... ; }
function4 () { ... ; }

main () {
  function1
  function2
  function3
  function4
}

main

Note: using amain function allows you to define and call functions in any order, and allows you to define your functions (other than main() itself) at the end of the script so that the main code comes first.  Otherwise you can get errors in situations where, e.g., your main non-function script code calls function2 before it is defined.

as noted above, each function call can, or should, have explicit arguments passing in the values they will use.

BTW, for the case statement mentioned above:

case "$var" in
  1) function1 ;;
  2) function2 ;;
  3) function3 ;;
  4) function4 ;;
  *) error 1 'Unknown case' ;;
esac

That case statement would be a lot harder to read if each case had 5 or 10 or more lines of code.


You should separate your responsibilities. Currently your function recCycleLength (which should be named rec_cycle_length to conform with Python's official style guide PEP8) does two things, calculating the return value and caching it in a passed dictionary. It would be better to outsource the latter to a decorator, like this one (which is the fastest memoization decorator for a single-valued function I know of):

def memodict(f):
    """ Memoization decorator for a function taking a single argument """
    class memodict(dict):
        def __missing__(self, key):
            ret = self[key] = f(key)
            return ret
    return memodict().__getitem__

@memodict
def rec_cycle_length(n):
    if n == 1:
        return 1
    elif n % 2 == 0:
        return cyc_len = rec_cycle_length(n//2) + 1
    return rec_cycle_length(3*n+1) + 1

You can even use this decorator on maxCycle when changing it to accept only one argument, the tuple (a, b). You could also be using max with a generator expression here:

@memodict
def max_cycle(bounds):
    a, b = bounds
    return max(rec_cycle_length(n) for n in range(a, b + 1))

(Use xrange in case you are using python 2.x.)

Your code on module level should be guarded by a if __name__ == '__main__': guard. You could also use map and sorted to get rid of quite a few lines of code:

if __name__ == '__main__':
    for line in sys.stdin:
        bounds = tuple(sorted(map(int, line.split())))
        print(" ".join(bounds), max_cycle(bounds))

This allows you to do e.g. from filename import rec_cycle_length in another script to reuse a function defined here.

Note that even though str.format is awesome, it is not needed here.

Since you seem to be using python 3.x, you might want to use functools.lru_cache instead of this decorator, like so:

import functools

@functools.lru_cache(2**10)
def rec_cycle_length(n):
    ...

At least on my machine it is a lot faster for some use cases (because the cache will not grow without bounds, making it better when there are few repetitions, i.e. many cache misses.) It is, however, only included in python >= 3.3.


Make a list's elements consecutive by an integer n

remove() is most likely linear. If so, the entire method has a quadratic time complexity. However there is a linear algorithm, which does not rely on remove():

    int kept = 0;
    int unknown = 1;
    while (unknown < size) {
        if (Math.abs(data[kept] - data[unknown]) == n) {
            data[++kept] = data[unknown];
        }
        unknown++;
    }
    erase(kept + 1, size);  // or whatever method you have to delete the tail of the array
    return unknown - kept > 1;

A perk benefit of this approach is that you don't need to reassign isChanged every time an element is removed.


Nice doc-strings. I enjoyed seeing your code. I have just a few comments.

Use built-in functions instead of rolling your own

My guess would be that you could improve the efficiency of uniquify and also make the code more expressive/easier to digest by returning the list version of a union of all the sets in querysets rather than rolling your own solution. Something like this should work (I didn't run it):

full_set = set().union(*query_sets)
return list(full_set)

Another option relying on built-in functionality would be to return a set out of the chaining you already do:

return set(chain(*queryests))

In fact coming back to this, I think you should return a set. It doesn't seem that you later need a list since you're just checking membership. I believe checking set membership is much faster than checking list membership.

Logic

I apologize if I am misunderstanding your logic, but it seems in search_for_term that you want to return early when you find at least number number of results. However, right now you only return early if you find exactly that number of results. Wouldn't you want to modify your early return as:

    if len(objects) >= number:
        return objects

If not it might be helpful to add a comment explaining the logic of returning when you have exactly a certain number of results.

Little nits

Notice you've got a typo in your parameter name queryests. I would recommend using snake_case as in my example above.

Since you're only using operator.or_, consider importing just that function.


I'm going to talk about variable naming. I can't read your code and understand what's happening which indicates that your code isn't self-explanatory. One step in accomplishing that is to give variables meaningful names:

lastRow is good! Otherwise..

prods - what is this? a dictionary of product keys? why not productList or something similar?

prod how is this different than prods?  Should it be productListKey?

tRange, rv, c, i and tmp - I have no idea what they should be doing - except for i because it's pretty standard.

cStart, currVal and i - you never use them. But if you did  - why not just use the entire word for the description? currentValue and cellStart

Speaking of currVal, cStart, i and tmp - When you don't define your variable, VBA will declare it as a Variant, which are objects:

  Performance. A variable you declare with the Object type is flexible
  enough to contain a reference to any object. However, when you invoke
  a method or property on such a variable, you always incur late binding
  (at run time). To force early binding (at compile time) and better
  performance, declare the variable with a specific class name, or cast
  it to the specific data type.

By not declaring variables, you could possibly be paying a penalty.

What is rv anyway?

Also you are using (rng as Range) in your function - but you're passing it ByRef by default. I don't see any need to do that, so ByVal testRange as Range would be better.

Logic

As far as I can tell you make a dictionary of all values with an interior color. Then you make a dictionary of all values `in the same range as the first dictionary. Then you compare the dictionaries. Since you're already looping through the range for the second dictionary, I'm not sure what kind of speed gains you're getting considering you could just loop through once.

As for finding unfilled cells - I think they are the same. The color is more accurate than colorindex. I'd still use the color property though as all the rest of my code would use color before colorindex.


Different method to calculate blob area in OpenCv

Declare drawingMatCount once before the loop
cv::drawContours(drawingMatCount, contoursIn, i, 0, -1, 8);  at the end of the loop

BTW: this is not the blob area, its the contour area, including the holes.


Connect Four: Bitboard checking algorithm

The bit-check-board can be indeed improved. This is what I got by just joining together common parts, even though I guess it could be further improved:

(defn check [c x]
  (bit-and c (bit-shift-right c x)))

(defn bit-check-board
  "Checks whether given bitboard is a win."
  [bitboard]
  (let [positions [6 7 8 1]
        coords (mapv (partial check bitboard) positions)]
    (apply bit-or (map check coords (map #(* 2 %) positions)))))

Also, you can reduce the repetition in the insert function by better modularize the code and use higher order functions with a pre-calculated transformation table:

(defn insert* [board x y]
  (bit-insert board (- 5 y) x))

(defn get-transforms [num]
  (if (= 1 num)
    [identity insert* identity]
    [identity identity insert*]))

(defn insert
  "Inserts symbol for given player (either 1 or 2) at specified x and
   calls bit-insert for corresponding bitboard."
  [boards x player-num]
  (let [y (get-y (boards 0) x)
        board0 (assoc-in (boards 0) [y x] (player player-num))
        transfv (get-transforms player-num)]
    (mapv [board0 (boards 1) (boards 2)] transv)))

If you're on Clojure < 1.4 than you have to change (mapv ...) in (vector (map ...))


while True:
    now = datetime.now()
    # repeats = 1 if now.hour % 3 == 0 else now.hour % 3
    repeats = now.hour % 3 + 1

    if now.hour < 6:
        break

The repeats is not used in the condition of the break. Therefore you should reorder your code like this, to avoid computing things you don't need later:

    now = datetime.now()
    if now.hour < 6:
        break

    repeats = now.hour % 3 + 1

I was confused by the last line of code. I thought it would mean to ring the bell 3 times at 2 o'clock. What confused me was that now.hour does not correspond to my intuitive understanding of now anymore, since by the time the bell will ring, some time has passed.

To avoid this confusion, you should define a variable next_hour = now.hour + 1. When you then define repeats = (next_hour - 1) % 3 + 1, that may look even more confusing because of the - 1 at the beginning and the + 1 at the end. That's probably why you considered repeats = 3 if next_hour % 3 == 0 else next_hour % 3, and it's good that you did that.

Continuing with your code:

    # report on whole hour
    if now.minute == 0:
        for _ in range(repeats):  # bell the hours
            play(bell_sound)
        time.sleep(60 * 58)  # save the computation

I hope that each bell takes only a few seconds. As soon as they become longer, you might miss the next hour completely. The "save the computation" part feels dangerous to me. This is because on practically all operating systems you can put a process to sleep and later resume it. I don't know how exactly this affects the clock and the measurement of datetime.now(), but that's definitely something you should experiment with.

It's better to define a high-level overview first:

def ring_until_midnight():
    current_hour = datetime.now().hour
    if current_hour < 6:
        break

    while current_hour < 23:
        wait_until_hour(current_hour + 1)
        ring_the_bell(current_hour + 1)
        current_hour += 1

This raises the question what to do if the hour steps forward fast, such as when the daylight saving time changes. Since you probably don't want the clock to ring 5 times in a row, it's better to replace the last line above with:

        current_hour = datetime.now().hour  # instead of current_hour + 1

Next, it's time to fill the missing details, which are wait_until_hour and ring_the_bell. For wait_until I propose this simple solution:

def wait_until_hour(hour):
    while datetime.now().hour < hour:
        time.sleep(1)

Note that I intentionally wrote < hour instead of != hour. Just in case the process is stopped for 3 hours. If I had written != hour, the code would continue to wait until the next day. Again, it depends on your exact requirements whether < or != is appropriate in this situation. In any case, you have to make this choice consciously.

Having a possible clock offset of 1 second (from the above sleep(1)) sounds acceptable to me. If you need more precision, you can say time.sleep(0.1) instead as well.

The second detail, ring_the_bell, is similarly simple:

def ring_the_bell(hour):
    repeats = (hour - 1) % 3 + 1

    for _ in range(repeats):
        play(bell_sound)

Now that I think of it, in the definition of ring_until_midnight above, I made an unfortunate choice:

        ring_the_bell(current_hour + 1)

This should rather be:

        ring_the_bell(datetime.now().hour)

The point is that during all this waiting, there is much that can happen, and there is no guarantee that waiting for "the next hour" will finally arrive at exactly that hour. Therefore better ask for the then-current time again.

When you build your programs out of composable pieces like these, you will find that you can reuse some parts by just copying them to your next project, which is good because it saves you the work of writing the same code over and over again, plus you will build up your library of small, hopefully tested code that you know you can trust.

As you saw in the process I outlined above, even writing a simple ring-the-bell program can be made quite complicated. It needs lots of decisions that you might not think about when you first decide to write such a program. The complexity arises mainly because this program is dealing with time and measurement and calendars, which always gets complicated. That's the way it is.

You also saw that it is of utmost importance to get the exact wording right in every line of the code. Is saying "the current hour" really the best way to express your requirement? What does "current" mean, when was it measured, for how long is that measurement valid, what happens in between? Lots of questions, and you sometimes have to revise your initial program. I'm quite experienced, and I didn't get it right either on the first attempt.


Periodically checking for internet connection

I know this may sound silly but what exactly do mean by connected to the internet? You're going to have to define what this means to your application.

In your example, if "www.google.com" goes down then the user is no longer connected to the internet and this is not necessarily true. Last time I checked, google isn't the internet (although it is very close).

The problem all boils down to the fact that the user may be connected to some part of the internet but unable to reach other parts due to corporate/national firewalls, broken equipment, wrongly configured hosts files etc. Or just a very zealous ISP who insists every one go through their gateway googlez.net to show you ads on every google search.

It makes more sense to test for an URL that actually means something for your application (I can't tell what this is going to be used for so I can't offer anything more specific). Like a service that you interact with.

As you see it's a tricky question and you need to answer some of these questions before you can come up with a good solution.


Python command line tool for compiling py files to exec files on Mac

I recommend that you read PEP 8.

It's advised against doing import os, re. Instead have one line dedicated to each import.
You should have an empty line between importing third party libraries and standard library ones.
In Python it's standard to use snake_case.
You should only have one space either side of the equals sign when performing assignment.
Rather than doing path is not '' you should use the != operator.
'\.py$' is deprecated in Python 3.6, and will become a syntax error in a future version of Python. Instead use r'\.py$'.
Don't mix ' and " string delimiters. Unless it's to do "'".
You don't need to use a \ for line breaking as your within brackets.
You should have the + in front of the next line, rather than the end of the previous line.

Your variable names are crap. path, name FILE, cFILE, PATH. The reason you need your comments is because of this.
If you fix your variable names your comments are useless.
Don't make a list to then call os.system just call it straight away.
Use pathlib, it singlehandedly makes your code ridiculously simple.
Put your code in an if __name__ == '__main__' guard. You don't want to destroy things by accident.

untested:

"""(PYCX) PYthon to Cython to eXec, a unix command line util
Usage:
  pycx FILES... [-o DIR --show --delete --run]
  pycx --help

Options:
  FILES              one or more python files to compile
  -o --output=DIR    output directory
  -s --show          show output from exec compiling
  -d --delete        delete the c file after compiling exec
  -r --run           run the exec after compiling
  -h --help          show this screen.
"""
import os
from pathlib import Path

from docopt import docopt

INCLUDES = '/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/include/python3.7m'
LIBRARY = '/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib'
HIDEDATA = '&>/dev/null'

def main(args):
    for path in args['FILES']:
        path = Path(path)
        if path.suffix != '.py':
            print(__doc__)
            continue

        output = Path(args['--output'] or '') / path.stem
        c_file = path.parent / path.stem + '.c'

        os.system(f'cython --embed -o {c_file} {path}')
        os.system(
            f'gcc -v -Os -I {INCLUDES} -L {LIBRARY} {c_file} '
            f'-o {output} -lpython3.7 -lpthread -lm -lutil -ldl '
            + HIDEDATA if not args['--show'] else ''
        )

        if args['--delete']:
            os.system(
                f'find {path.parent} -name "{path.stem}.c" -type f'
                f'|xargs rm -f'
            )

        if args['--run']:
            os.system(f'{output}')

if __name__ == '__main__':
    main(docopt(__doc__))


Type Name or Alias via Reflection for TT Code Generation

bool bAlias

Don't use Hungarian notation on names. When you look at the parameter, you can already see that it's a bool, there is no reason to repeat that in the name.

String name = null;

Since it seems you never want to use that null value, don't initialize the variable at all.

Also, it's more common to write string instead of String.

name = (bAlias) ? GetAliasName(nullable, bFullQualified)
    : (bFullQualified) ? nullable.FullName : nullable.Name;

What's the point of the parentheses around bAlias and bFullQualified. They don't seem to serve any purpose.

String[] names = type.GenericTypeArguments
    .Select(t => GetActualTypeName(t, bAlias, bFullQualified))
    .ToArray();

I think names is too general here. I think something like typeArgumentNames would be better here (even if it's significantly longer).

Also, String.Join() can accept IEnumerable<string>, so the ToArray() is unnecessary here.

name.Substring(0, name.IndexOf('`'))

Wouldn't this be more readable as name.Split('`')[0]? (It would also be less efficient, but that might not matter to you.)

String.Join(",", names)

I realize this is for generated code, so beauty does not matter much, but I would still prefer to add a space between the type arguments, i.e. String.Join(", ", names).

using (var provider = new Microsoft.CSharp.CSharpCodeProvider())

Neither CSharpCodeProvider not its base class, CodeDomProvider override Dispose(), it's only there because they inherit from Component.

This means that there is no need to use using here. But even if you know this, you might still choose to include the using, just to be on the safe side.

Also, since you're already using CSharpCodeProvider for this, why not use it to replace your whole GetActualTypeName()? You would lose the choice of specifying the form of the output, but it might be worth it for so much simplification.


Naïve Prime Factorization in Clojure Pt. 2

All that the lazily-find-prime-factors function needs is the (primes) sequence. You just keep trying each in turn. Your smallest-factor-of drops the failed factors, but forgets what it has done, so you have to do it again for the recursive call.

And I'd rename your is-factor-of? function:

=> (is-factor-of? 4 2)
true
=> (is-factor-of? 2 4)
false

... reads wrongly. I've called it divides-by?.

I end up with ...

(defn lazily-find-prime-factors [n]
  (letfn [(rec [remaining remaining-primes]
            (when (> remaining 1)
              (let [rp (drop-while #(not (divides-by? remaining %)) remaining-primes)
                    small-prime (first rp)]
                (lazy-seq (cons small-prime
                            (rec (quot remaining small-prime) rp))))))]
   (rec n (primes))))

Factoring the problem this way, you can easily plug in an efficient way of generating primes.


The Job class has public members, so it's simpler to make it an aggregate:

struct Job {
    int index;
    int time_slot;
    int profit;
};

Then, use std::tie to simplify the comparison operators: (operands to these operators should be marked as const, which you didn't)

bool operator<(const Job& lhs, const Job& rhs)
{
    return std::tie(lhs.time_slot, lhs.profit) < std::tie(rhs.time_slot, rhs.profit);
}

// implement other operators in terms of <

You == is not consistent with other comparison operators, which is confusing and likely to cause problems.

Also note that if (condition) { return true; } return false; should be changed to return condition; for clarity.

This is convoluted:

Job j1(1, 1, 3);
Job j2(2, 3, 5);
Job j3(3, 4, 20);
Job j4(4, 3, 18);
Job j5(5, 2, 1);
Job j6(6, 1, 6);
Job j7(7, 2, 30);
std::vector<Job> vect = { j1,j2,j3,j4,j5,j6,j7 };

It should be simplified to

std::vector<Job> vect {
    {1, 1, 3}, {2, 3, 5}, // ...
};

This:

auto order = [&]() {
    auto it = vect.begin();
    while (it + 1 != vect.end()) {
        if (*it == *(it + 1)) {
            it = vect.erase(it);
            continue;
        }
        it++;
    }
};
order();

should be

vect.erase(std::unique(vect.begin(), vect.end()), vect.end());

(provided that I understand the code correctly).

And this:

std::for_each(vect.begin(), vect.end(), [](Job i) {std::cout << i << " "; });

is a complicated way of writing

for (const auto& job : vect) {
    std::cout << job << ' ';
}

or

std::copy(vect.begin(), vect.end(),
          std::ostream_iterator<Job>{std::cout, ' '});


Object to object mapping verification - is this extension method useful?

Minor nitpick first:

public static T2 ToDto<T1,T2>(this T1 obj, params Expression<Func<T1, dynamic>>[] items) where T1 : class
{

I think putting generic type constraints on a new line makes them easier to spot and adds to readability (especially with long signatures) - consider:

public static T2 ToDto<T1,T2>(this T1 obj, params Expression<Func<T1, dynamic>>[] items)
    where T1 : class
{

I really don't like T1 and T2 for generic type parameter names. T is ok when it's the only parameter, but I'd much, much rather like to see TSource and TResult - it makes it much clearer which one serves which purpose, at a glance.

This also instantly makes it easy to find source a much more meaningful name than obj. I'm all for readable identifiers, so I would like to see props renamed to properties, and eo to expandoObject, or perhaps just value - I will be using these identifiers for the remainder of this post.

I like that you're using var - I don't understand why you're not using it here, since JsonConvert.SerializeObject returns a String:

string json = JsonConvert.SerializeObject(value);  // need json.net

That said, the comment isn't necessary. If you referenced Json.net from a NuGet package, the IDE will tell you when/if a package is missing. If you referenced Json.net from an assembly, the project will fail to build and under "references", Newtonsoft.Json will appear problematic - the comment really doesn't help with anything, it's just noise.

In this block:

if (member != null && body.Member is PropertyInfo)
{
    var property = body.Member as PropertyInfo;
    if (property != null)
        properties[property.Name] = source.GetType().GetProperty(property.Name).GetValue(source, null);
}

The condition if (property != null) will always be true, because body.Member is PropertyInfo is necessarily true in that branch. Hence it can be simplified to this:

if (member != null && body.Member is PropertyInfo)
{
    var property = body.Member as PropertyInfo;
    properties[property.Name] = source.GetType().GetProperty(property.Name).GetValue(source, null);
}

The else branch has a redundant cast - you defined unary as item.Body as UnaryExpression; hence, unary already has the reference you're getting in this superfluous declaration:

var ubody = (UnaryExpression)item.Body;

Just use unary, you don't need ubody at all.

I haven't tested it, but the type parameter in DeserializeAnonymousType<object> seems superfluous as well - Activator.CreateInstance<TResult>() will create a TResult object.. that you can readily return - so instead of this:

var json = JsonConvert.SerializeObject(value);
var anon = JsonConvert.DeserializeAnonymousType<object>(json, Activator.CreateInstance<TResult>());
return ((JObject)anon).ToObject<TResult>();

You'd have that:

var json = JsonConvert.SerializeObject(value);
return JsonConvert.DeserializeAnonymousType(json, Activator.CreateInstance<TResult>());

Notice I'm letting the compiler infer the generic type parameter here.

Lastly, the way chained reflection methods are laid out isn't consistent between the if and the else branch - one has it like this:

properties[property.Name] = source.GetType().GetProperty(property.Name).GetValue(source, null);

The other has it like that:

properties[property.Member.Name] = source.GetType()
    .GetProperty(property.Member.Name)
    .GetValue(source, null);

I like how putting each instruction on a new line makes it easier to see what's going on. Some may argue that it's even easier when the dots line up:

properties[property.Member.Name] = source.GetType()
                                         .GetProperty(property.Member.Name)
                                         .GetValue(source, null);


There are a few major differences between what I understand from your code and what I understand from the post you mention.

Inheritance vs Nesting
Your code suggests that there is a subclass for each tested method, although the post talks about nested classes:

  The structure has a test class per class being tested. That’s not so
  unusual. But what was unusual to me was that he had a nested class for
  each method being tested.

Class per test vs Class per Method
Also, your code example implies that each class contains a single test, which loses all meaning for the class. The post talks about a class per method tested, which mean that it may contain more than one test, but all tests are relevant to the same method.

using Xunit;

public class TitleizerFacts
{
    public class TheTitleizerMethod
    {
        [Fact]
        public void ReturnsDefaultTitleForNullName()
        {
            // Test code
        }

        [Fact]
        public void AppendsTitleToName()
        {
            // Test code
        }
    }

This kind of structure is very similar to how an RSpec test would be structured, having multiple layers of describe blocks for different scopes - class, method, feature...

describe HomeController do

  let (:fixture) { double('fixture') }

  before(:each) do
    # something before each test
  end

  describe '#get_home' do

    before(:each) do
      expect(repository).to receive(:get_id).with(1).and_return(entity)
    end

    let(:result) { subject.GetOne(1) }

    it 'returns result' do
       expect(result).to_not be_nil
    end

    it 'returns entity data from database' do
       expect(result.content).to eq entity
     end
  end
end


Generating combinations of specific values of a nested dict

For non-trivial list comprehensions such as

multi_config_flat = { key[:-1] + (key[-1][6:],) : value for key, value in flat.items() if key[-1][:5]=='multi'}

You should split it onto multiple lines, i.e.

multi_config_flat = {key[:-1] + (key[-1][6:],): value
                     for key, value in flat.items()
                     if key[-1][:5]=='multi'}

This:

key[-1][:5]=='multi'

should be

key[-1].startswith('multi')

This:

if len(multi_config_flat) == 0: return

is equivalent (more or less) to

if not multi_config_flat:
    return

The latter also catches the case of multi_config_flat being None, but that won't be possible in this context.

This:

for key, _ in multi_config_flat.items():

is not necessary; simply iterate over keys:

for key in multi_config_flat:

This is fairly opaque:

reduce(operator.getitem, setting[:-1], config)[setting[-1]] = value

Probably you should assign the output of reduce to a meaningfully named variable, so that your code is more clear.


Products excluding each element of the array

Time complexity-wise, I think not. You're required to 'visit' all numbers, and your solution is O(n), so that can't be improved.

Code clarity could be improved, as it's not very obvious what the intention is. Some comments would help that.
I think shifting indices by 1 might make it clearer (left[i+1] = arr[i] * left[i]), but then maybe not because it'd mess up the last loop.

Have you explored different algorithms? I wonder if straightforward memoization makes a very clear solution for this.


IDs
Avoid IDs for styling. It's ok to use them to identify elements with JavaScript, but the specificity in CSS can make structuring the styles tricky.
Names such as buttons, yes and no are very generic, that could easily be needed more than once in a document.
Also try to be more consistant with the style of classes/names/IDs. For example, shownotice has no underline, but consent_notice does. Consider using hyphens instead of an underlines in order to match the general style of CSS, which uses hyphens, as in background-color.
HTML
"true" is not a valid value for the attribute for the attribute hidden. As a boolean attribute hidden is either present without a value (or, if you prefer use the value "hidden" as in hidden="hidden") or not present. hidden="false", for example, would still hide the element.
JavaScript
Declare your variables with const or let (or var if you need to support very old browsers).
In JavaScript it is convention to write variable names in camelCase and not with underlines.
You could be more consistent when retrieving elements by ID and use either querySelector or getElementById, but not both.
Don't use on... properties to assign event handlers. Use addEventListener.
Use the boolean negator ! to toggle boolean values:
consent_elem.hidden = !consent_elem.hidden;


what about?

var date1 = DateTime.Parse("2/29/2000");
var date2 = DateTime.Parse("2/28/2009");

var years_old = date2.Subtract(date1).TotalDays / 365.25;


OOP demonstration in C++17 using a Pokémon

It looks like all the Pokemon member variables should be private, not public.
The Pokemon constructor takes catch_rate as an int, where it should be a float.
The Pokemon constructor could std::move the string argument into m_type.
Pokemon::type() could return by const& to avoid an unnecessary copy.
Castform::m_forms is not used anywhere, but should probably also be static and const.
When overriding a virtual function, we should always use the override keyword (and arguably also the virtual keyword):

virtual bool attempt_catch() override { ... }

Use the C++11 <random> functionality, not rand().

Run-time polymorphism with virtual functions in C++ is driven by a need to treat objects of different types with the same interface. Unfortunately, this example lacks the motivation for it:

Currently the attempt_catch() function could be implemented in the Pokemon base-class with no problem.
There is no example of differing behavior (i.e. there should be a second pokemon type implementing a different attempt_catch() function). Maybe an attack function would work better?
There is no demonstration of using the different types through the same interface. In C++ this usually boils down to storing different types in the same container (e.g. iterating a std::vector<std::unique_ptr<Pokemon>> and calling the virtual function). However, it might be simpler to pass two different pokemon types to a function taking a Pokemon reference:

void throw_pokeball(Pokemon const& target) { target.attempt_catch() } // or something

Depending on what this is actually for, I'd suggest approaching things in a "problem -> solution" way, both in terms of what the code does (see above), but also in terms of language development and why these features exist. i.e.

"Here's what programmers used to have to do without this language feature [...]. It sucks because [...]"
"This language feature allows us to do [...] safely and easily because [...]".

Note that there are many different types of both static and dynamic polymorphism in C++ (e.g. function overloading, implicit conversions, function objects, template parameters (traits, tags, etc.)), not just inheritance and virtual functions.


First off, your code doesn't seem very optimal. This doesn't effect the speed as far as I can see, but does effect the readability, which may limit the help you get here.

Why do you create a second div inside #grid?
Why do you assign the styles of the cells twice (inline to the style attribute and a second time via the class)?
Why are you using a class at all? A selector such as `#grid > div > div' would be easier.

Here is the simplified code I used: http://jsfiddle.net/jJa8L/2/

Some experimentation show for me that the biggest speed hog seems to be the absolute positioning. When I comment it out, then I get speed improvements of 30 to 50% (40-45 fps) in Chrome. I haven't had a chance to try it out, but I'd try using a table layout (either using a <table> directly in the HTML, or using display: table-* in the CSS).

EDIT: I just discovered one certain optimization: Moving the font property from the class to more global rule (body or #grid), raises the fps in Chrome to 35-38. See http://jsfiddle.net/jJa8L/3/

EDIT 2: Ok, here's a version with table layout: http://jsfiddle.net/jJa8L/4/ It's still at 40-45 fps.

EDIT 3: No idea why I didn't think of this before: Simply let the cells flow with display: inline-block giving #grid an appriopriate width. http://jsfiddle.net/jJa8L/5/ This is  slightly faster (42-47 fps).

EDIT 4:
I just had another idea: There is a considerable speed up in Firefox and IE (but not Chrome for some reason) if you hide the grid while updating the cell texts: http://jsfiddle.net/jJa8L/8/


Python generator to produce lattice points on an n-simplex.

Concatenating numpy arrays isn't a really good idea because that's not how they were designed to be used.

A better way might be this:

def walk(num_dims, samples_per_dim):
    """
    A generator that returns lattice points on an n-simplex.
    """
    values = np.arange(samples_per_dim) / (samples_per_dim - 1)
    for items in itertools.product(values, repeat = num_dims+1):
        if sum(items) == 1.0:
            yield items

Basically, we iterate over all possible combinations of those points, and filter out the invalid ones. This may seem wasteful, but since itertools is written in C, its probably actually faster then your solution. It produces tuples rather then numpy arrays.


Personally, I would separate this into multiple functions:

public StatusCode GetStatus( ... )
{
    CardPort cardPort = findCardPort(card, port);
    if (cardPort == null) {
        return StatusCode.CARD_PORT_NOT_FOUND;
    }

    Sim sim = cardPort.getSim();
    if (sim == null) {
        return StatusCode.CARD_WITHOUT_SIM;
    }

    User user = sim.getUser();
    if (user == null) {
        return StatusCode.SIM_WITHOUT_USER;
    }

    return null; /* IMO, should be StatusCode.OK instead of null */
}

public bool ShouldInvokeService( ... )
{
    return GetStatus( ... ) == null;
}

Now you don't need the nested indentations to track the status state -- just check conditions until you either know everything is okay, or you run into a problem.


Maybe it's better to return error in JSON (if FAIL constant isn't JSON yet)

echo json_encode(array('result' => false));

instead of

echo FAIL;

or return HTTP error code

header('HTTP/1.1 500 Internal Server Error');

And we can simplifify function get_data like this:

if(mysql_num_rows( $events_list )) // check if the query returned any records
{
    $mysql_record = mysql_fetch_array( $events_list );    // parse mysql result cursor
    return array(
        'e_id'                     => $mysql_record['eid'],
        'edisplay_date'            => $mysql_record['display_date'],
        'eword_of_the_day'         => $mysql_record['word_of_the_day'],
        'eword_of_the_day_meaning' => $mysql_record['word_of_the_day_meaning'],
        'ethought_of_the_day'      => $mysql_record['thought_of_the_day'],
        'ecrazyFact_of_the_day'    => $mysql_record['crazyFact_of_the_day'],
        'ejoke_of_the_day'         => $mysql_record['joke_of_the_day'],
    );
} else return false;


First thoughts:

If an operation can fail, it is generally good practise to make this explicit in the API by returning a Try instead of an Either.
The duplicate code seems to stem from the fact that Money operations are only valid on Currencies of the same type. Scala gives you the power to have this check at compile time.

Example Code:

object Money {
  sealed trait Currency
  case object GBP extends Currency
}
case class Money[T <: Money.Currency](amount: BigDecimal) {
  private def calculate(that: Money[T])(f: (BigDecimal, BigDecimal) => BigDecimal): Money[T] = {
    copy(amount = f(this.amount, that.amount))
  }
  private def compare(that: Money[T])(f: (BigDecimal, BigDecimal) => Boolean): Boolean = {
    this.amount > that.amount
  }
}