Analyse an Nginx access log with awk and produce a report

The biggest problem, and the hardest to fix, is calling awk, sort | uniq -c | sort -r, sometimes within a loop, when you could implement all that more efficiently in Python. It's ugly to do this in multiple sub-shells and multiple processes. But that would take a substantial rewrite.

You are not using the class attributes here:

class NginxReporter():

    location = None
    template = 'templates/default.html'
    html = None

So you could just delete these from your class.

The constructor is not well designed. You're trying to do too much, for two very different use cases:

In one use case, you use it just to set a logfile location, and then you call other methods to do the real work
In another use case, the constructor would call the other methods

It's better to decide one of these ways, stick with it, and simplify the code accordingly.

This method is strange:

def scpdownload(self, remotelocation=None):
    if remotelocation:
        check_output(['scp', remotelocation, self.location])

You allow calling it without params, or null param, to do nothing? This is messy and confusing. It would be better to require a param.

Btw, downloading a file with scp doesn't sound like it belongs to the class. It violates the single responsibility principle: a class should have one clear purpose (parse nginx log files), and nothing else.

This could use some reworking:

if out == '' and output.poll() != None:
    break
if out != '':
    block = out

Like this:

if not out:
    if not output.poll():
        break
else:
    block = out

You open a file for reading but you're not closing it:

file = open(self.template)
block = Template(file.read())
print block.substitute(self.html)

The right way to do is using with:

with open(self.template) as fh:
    block = Template(fh.read())
    print block.substitute(self.html)

I also renamed file to fh because file is a class in Python 2.x

If you want to temporarily comment out one line,
it's better to use # instead of """ ... """ which is recommended for multi-line comments and docstrings:

report = NginxReporter('access.log')
#report.scpdownload("sshuser@server.com:/path/to/nginx/access.log")
report.parse()
report.output()


It doesn't necessarily bother me that so much of our styling code is outside of the init method (though I would change some of this up--I'll get back to that).  What bothers me is that it seems it's all directly in viewDidLoad.

I don't know about you, but for me, there's regularly lots of things to set up in viewDidLoad.  Here, you've committed 21 lines of viewDidLoad code to setting up these buttons.  Once we add code for a few other UI elements, plus code for anything else we want to set up in viewDidLoad, the method very quickly becomes a mega-do-too-much-method.

What I'd rather see is a method to contain all the code that sets up the buttons, and let viewDidLoad call that method.  I'd much rather see:

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupButtons];
    [self setupLabels];
    [self checkWebForSomething];
}

We've got who knows how many very distinct tasks that all want to happen in viewDidLoad (or any other view controller life-cycle event).

If we separate these tasks out into distinct methods, it makes maintenance easier in the future.  I don't want to spend time skimming through the UI code when I really just need to fix something in the code that does the checkWebForSomething stuff (and vice versa).

Now, with all that said, let's talk about the specifics of your initWithFrame: method, shall we?

I don't mind that we set things like our corner radius and shadow off set in init.  I don't even necessarily mind that we set our font and have a hard coded height for the button.  The most bothersome of these 4 things to me would be the hard coded height, but there's plenty of Apple precedent for UI elements with fixed height or width.

What bothers me are the preset colors.

Honestly, I think rather than initWithFrame:, we should be seeing a method that looks more like:

- (UIButton *)initWithFrame:(CGRect)frame
                      title:(NSString *)title
            foregroundColor:(UIColor *)foregroundColor
            backgroundColor:(UIColor *)backgroundColor
                shadowColor:(UIColor *)shadowColor;


Function modelExist should check if model exists and return boolean. Your function does something completely different. It only needs that check for its job.

public function modelExists(int $modelId): bool;

To check existence of a row, you don't need all its columns. Select just 1 (literally) and check if you have received a row from the query or not.

SELECT 1 FROM models_web_tbl WHERE model_id = ?

Create another function for the insert

public function insertModel(int $modelId, string $modelWeb): void

Maybe you wanted to combine it into another function.

public function tryInsert(int $modelId, string $modelWeb): bool
{
  if ($this->modelExists($modelId)) {
    return false;
  }
  $this->insert($modelId, $modelWeb);
  return true;
}

Don't connect to database again for every query

class test
{
  private PDO $connection;
  function __construct(PDO $connection) {
    $this->connection = $connection;
  }
  function modelExists(int $modelId): bool
  {
    // ...
    $this->connection->prepare($sql);
    // ...
  }

  function insert(int $modelId, $modelWeb): void
  {
    // ...
    $this->connection->prepare($sql);
    // ...
  }
}

$connection = connect();
$test = new test($connection);
  // I don't know why it was important to assign 'twitter' to a variable first :)
if (!$test->tryInsert($model_id, 'twitter')) {
  // echo definitely dont belong into exists-check function
  echo "found";
}


Is there any room for improvement?

Yes there is.

You have a Diophantine equation \$3x + 5y = N\$, (\$3x\$ and \$5y\$ being the number of occurrences of 5 and 3 respectively. A base solution is \$x = 2N, y = -N\$. All other solutions are in form of \$x = 2N - 5k, y = -N + 3k\$. That is, you just need to find \$k\$, which makes both numbers positive. Such as k = (N-1)/3 + 1 (if x becomes negative, there are no solutions).

Bottom line is that neither the loop nor the special cases are needed.

See Wikipedia article for details.

Edit: Paper exercise as requested:

Let N = 8. Base solution: x = 16, y = -8. (16*3 - 8*5 = 48 - 40 = 8).

k = (8 - 1)/3 + 1 = 3. x' = 16 - 3*5 = 1; y' = -8 + 3*3 = 1.

3*x' + 5*x' = 3 + 5 = 8.

Edit: another exercise.

Let N = 30. Base solution: x = 60, y = -30.

k = 29/3 + 1 = 10.

x' = 60 - 5*10 = 10; y' = -30 + 3*10 = 0, yielding the decent number of 30 occurrences of 5 and 0 of 3; just as requested.


Preparing search criteria and results to be e-mailed

First off, stuff like my @aFields = split(/~/, $phParams->{sFields}); is a sign of something gone awry. You've just deserialized $phParams from a JSON object, so why isn't this just stored in a normal array?

There is no need to write $i < scalar(@aFields), just write $i < @aFields.

I have some comments wrt. this snippet:

my $value = $aValues[$i];
if ($phFieldInfo->{value_displays}) {
    $value = @{$phFieldInfo->{value_displays}}[$value];
} elsif ($phFieldInfo->{value_keys}) {
    $value = @{$phFieldInfo->{value_keys}}[$value];
}

You should always use warnings; and use strict;. The above won't run without warnings if warnings are on because @{$phFieldInfo->{value_keys}}[$value] should be written ${$phFieldInfo->{value_keys}}[$value].

Also, the whole thing can be written much shorter:

my $value = ${$phFieldInfo->{value_displays}}[$aValues[$i]]
    || ${$phFieldInfo->{value_keys}}[$aValues[$i]]
    || $aValues[$i];

Note: this isn't functionally identical with the original code, since I'm assuming that array refs at the keys value_displays and value_keys exists.

This essentially means "pick the first trueish value". Note that values like undef, 0 or the empty string won't be picked. If you want to be able to pick 0 or the empty string, replace || with //. This requires a recent version of perl (read: not ancient).

The rest looks reasonable. Fixing the stuff I suggested should cut the size a little, and I wouldn't try shortening it further.


Retrieving all directorie names (relative path)

Have you considered using SPLs RecursiveIteratorIterator and RecursiveDirectoryIterator? Like this:

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->directory), RecursiveIteratorIterator::CHILD_FIRST);
foreach($iterator as $path){
    if($path->isDir()){
        $cache = $this->GetInfoArray($path->__toString());
        isset($cache) ? $this->listing['directories'][] = $cache : "";
        unset($cache);
    } else {
        $this->listing['files'][] = $this->GetInfoArray($path->__toString());
    }
}

This will leave you with an array with two main nodes: files and directories. I wrote this for a PHP distributed test-and-build-on-commit system and it worked well. More info on the PHP SPL Iterators can be found here: http://www.php.net/manual/en/spl.iterators.php

By the way, the GetInfoArray is this:

private function GetInfoArray($path){
    $d = new SplFileInfo($path);
    if($d->getBasename() == "." || $d->getBasename() == ".."){
        return;
    } else {
        return array(
           "pathname"    => $d->getPathname(),
           "access"      => $d->getATime(),
           "modified"    => $d->getMTime(),
           "permissions" => $d->getPerms(),
           "size"        => $d->getSize(),
           "type"        => $d->getType(),
           "path"        => $d->getPath(),
           "basename"    => $d->getBasename(),
           "filename"    => $d->getFilename()
        );
    }
}

In the end, you're left with something like this:

$this->listing['files']['smiles.jpg']['pathname'] = "/srv/www/smiles.jpg"
$this->listing['files']['smiles.jpg']['access'] = "1323546894"
$this->listing['files']['smiles.jpg']['modified'] = "2316546521"
$this->listing['files']['smiles.jpg']['permissions'] = "744"
$this->listing['files']['smiles.jpg']['size'] = "12Kb"
$this->listing['files']['smiles.jpg']['type'] = "jpg"
$this->listing['files']['smiles.jpg']['path'] = "/srv/www"
$this->listing['files']['smiles.jpg']['basename'] = "smiles"
$this->listing['files']['smiles.jpg']['filename'] = "smiles.jpg"

What the heck, heres the class itself:

# Done

class DirectoryReader{
    private $directory;
    private $listing;

    public function __construct($directory){
        try {
            $this->directory = $directory;
            $this->listing = array();
            $this->ListDir();
        } catch(UnexpectedValueException $e){
            die("Path cannot be opened.");
        } catch(RuntimeException $e){
            die("Path given is empty string.");
        }
    }

    public function GetListing(){
        return $this->listing;
    }

    private function ListDir(){
        $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->directory), RecursiveIteratorIterator::CHILD_FIRST);
        foreach($iterator as $path){
            if($path->isDir()){
                $cache = $this->GetInfoArray($path->__toString());
                isset($cache) ? $this->listing['directories'][] = $cache : "";
                unset($cache);
            } else {
                $this->listing['files'][] = $this->GetInfoArray($path->__toString());
            }
        }
    }

    private function GetInfoArray($path){
        $d = new SplFileInfo($path);
        if($d->getBasename() == "." || $d->getBasename() == ".."){
            return;
        } else {
            return array(
               "pathname"    => $d->getPathname(),
               "access"      => $d->getATime(),
               "modified"    => $d->getMTime(),
               "permissions" => $d->getPerms(),
               "size"        => $d->getSize(),
               "type"        => $d->getType(),
               "path"        => $d->getPath(),
               "basename"    => $d->getBasename(),
               "filename"    => $d->getFilename()
            );
        }
    }
}

As a further note, you can also just call scandir($directory) and filter via is_dir() in a foreach.


Algorithm to Iterate All Possible Strings in Clojure

I figured out a faster, more functional programming-oriented algorithm for this problem -- see below. Besides that, your code overall looks idiomatic and was easy for me to understand, so I have no real criticisms in that area.

zipmap

zipmap is ideal for concisely constructing maps like your code->letter map:

(def code->letter
  (zipmap (map str (iterate inc 1)) (map char (range 97 123))))

;=> {"1" \a, "2" \b, "3" \c, ... "26" \z}

One way to avoid using flatten

Personally, I think using flatten is fine, but some view it as being somewhat hacky, and I've heard it said that if you find yourself using flatten, there is usually a better way to do what you're trying to do. In this case, I would use mapcat -- it's like map, but it handily concatenates the results together into a single collection.

EDIT: This doesn't work! Please disregard :)

...
(mapcat (fn [[k v]]
          (when (.startsWith number k index)
            (possible-strings number (+ index (count k)) (str acc v))))
        code->letter))))

or,

...
(mapcat (fn [[k v]] (possible-strings number (+ index (count k)) (str acc v)))
        (filter #(.startsWith number (key %) index) code->letter)))))

Functional programming

You're correct in that your algorithm is not (and cannot be) tail-recursive. This is because you're wrapping the recursive call to possible-strings within a filtering and mapping operation. I'm not familiar with the term "backtracking algorithm," but it does seem appropriate in this case. This initially struck me as the kind of thing you would do with a reduce, building up a string from scratch, however, you do have to keep "backtracking" to build up new strings using different groupings of digits. I might be wrong about this, but I don't think this is something you can do with tail-recursion, which means you can't use recur and there would be performance implications, especially for large inputs.

Here's another approach: write a function that takes a number and returns a list of possible arrangements of numbers from 1-26. Then just map the numbers to letters and you'll have your possible strings.

This function, which I'll call possible-arrangements, is a little complicated to write. My approach is to walk through the number string from the beginning and form a tree, looking at numbers 2 at a time and branching off for each possibility, each branch terminating once it reaches a list of numbers that can't be broken down any further. For example:

; *starred numbers are ones that are evaluated to see if they can be broken
; down further

                  *4125    ; 41 is not in range, so only one possibility...
                    |
                  4 *125   ; 12 can be 1 2 or 12, so we branch, etc.
                    /  \
                 1 *25  12 5
                   /\     |
                  /  \    |
      (4 1 ...) 2 5  25  12 5   = 4 1 2 5, 4 1 25, 4 1 12 5

; the result would be [["4" "1" "2" "5"] ["4" "1" "25"] ["4" "12" "5"]]

.

(defn possible-arrangements [^String n]
  (case (count n)
    1 [[n]]
    2 (let [each-digit (mapv str n)]
        (if (contains? code->letter n)
          [[n] each-digit]
          [each-digit]))
    (let [a       (str (first n))
          ab      (subs n 0 2)
          prepend (fn [x offset]
                    (map (partial cons x) (possible-arrangements (subs n offset))))]
      (if-not (contains? code->letter ab)
        (prepend a 1)
        (concat (prepend a 1) (prepend ab 2))))))

(defn possible-strings [^String n]
  (for [nums (possible-arrangements n)
        :let [chars (map code->letter nums)]]
    (apply str chars)))

This is still not a tail-recursive solution, but it's about 4 times faster, I think because it isn't having to perform 26 string operations for each digit of the input number.


Your code looks quite neat, although note that formatting, including spaces
around operators etc, line lengths, defining multiple variable per line, should follow a conventional style.

There are some issues, the main one being that compiling and running the code,
it does not work.  The problem is that

fopen(filename, "a+");

opens the file for  reading and writing but leaves the stream pointer at the
end of the file.  So any subsequent read will fail.   You need a rewind();
or equivalent (fseek etc) after checking that the file opened successfully.

After fixing the rewind, another issue is that fgets returns the input word
with a trailing newline, \n.  Your code ignores this and manages to work
because the strings that are written to and read from the dictionary also have
a trailing \n.  But this fails when a user enters a string that fills your
buffers, 19 characters or more.  In this case, the fgets call cannot read
the whole string and reads just the 1st 19 chars (and adds a terminating \0),
leaving the remaining chars in the input stream.  In this case there is no
trailing \n in the buffer.  The next time you read from stdin the 20th and 21st chars are
read and treated as the y/n answer.  Even if these chars happen to be "y", the
19-char word is written to the dictionary without a trailing \n, corrupting
the dictionary (try looking up abcdefghijklmnopqrsy - notice the 'y' at the end)

There are ways to fix these problems, for example you could try using
getline() to get the input string instead of fgets, although getline is
more tricky to use correctly.   Alternatively (as it is just an exercise)
just check the input string to confirm that there is a trailing \n (meaning
that the whole line was read) and reject the word and fflush the input if not.   To do things
properly you really need to remove the trailing \n from the user input string and
from the string read from the dictionary before comparing, and add \n back when writing to the
file.

Another issue is poor comments.  Comments must be useful; otherwise they are
just noise (and hence make reading the code more difficult than it need be).
All of your comments are just noise.

Note also that when opening the dictionary fails you should exit. There are numerous other issues, but I'll leave it at that for now...

EDIT

As no reviewers have commented on other issues, here are some other things I
spotted:

avoid use of constants such as 20.  Instead, define the buffer size with a
define and use sizeof where you need the buffer size. For example:

#define BUF_SIZE 20
...
char buf[BUF_SIZE];
fgets(buf, sizeof buf, stdin);

by using sizeof you guarantee that the size is correct - but note that
if you use it on a pointer, then you get the wrong value:

char *buf = malloc(BUF_SIZE);
fgets(buf, sizeof buf, stdin); // WRONG!!

in the latter case, sizeof returns the size of the pointer (typically 4
or 8 bytes) - you need to pass BUF_SIZE to fgets
define the file name in a constant or a #define and use the file name in the
error message on failure to open.  The message should be produced with
perror

const char *dict = "wordDic.dic";
...
FILE *file = fopen(dict,"a+");
if (file == NULL) {
    perror(dict);
    exit(EXIT_FAILURE);
}

notice that I exited immediately on failure (your code continues).
perror will produce a short error message on stderr that says why the file
could not be opened, not just that it couldn't.  Also note that I checked
the file pointer immediately, not after prompting the user, as you do.
you ask the user whether she would like to perform another search
(on success) but then ignore the answer.
the call to fflush is strictly unnecessary.  Buffered output like
fprintf (and printf) writes to file when it sees a \n in the buffer.  In
this case, your strings have \n embedded (from the fgets call) and so
fprintf will flush the buffer; the buffer is empty when fflush is
called.  The normal thing would be for the word in wordContainer to have
no \n and for fprintf to use a format containing \n - fprintf(filePtr,
"%s\n", word); - and again, no fflush is needed.
your

else
{
    printf("thank you for using this program,bye");
    exit(0);
}

exits before the final closing of the file and zero return.   Closing the file is good practice, although it will happen when the
program exits anyway.
I don't really like your variable names - three variables starting with
'word' is confusing.  I'd go for something like word for the user-entered
word, entry for the dictionary entry read from file and found to
indicate that the word was found in the dictionary.  That is a rather
personal preference though...
remember to put a \n on the end of lines that are printed, eg on exiting the
program.


if(isset($arr['d'])) $something = $arr['d'];
unset($arr['d']);

Well... If arr['d'] is not set, then you don't need to unset it. So this will save an unnecessary call sometimes:

if(isset($arr['d']))
{
    $something = $arr['d'];
    unset($arr['d']);
}

If you don't care for $something, then you can just do

unset($arr['d']);

Which is then one line. You could also write

if (isset($arr['d']) && ($something = $arr['d']) !== null) unset($ar['d']);

That is one line as well, but will fail to do what you like if $something is null. And from the point of readability it's questionable whether this is an improvement.


General rules of thumb:

In order to take advantage of connection pooling (and you should), database connections should be as short lived as possible. Create, use, then immediately destroy.
Single instance objects should always be agile (defined as not holding system resources e.g. db connections, file handles, etc.).
If you need a single instance object to handle a system resource, it should be done in a protected manner using a named mutex (naming makes a mutex available to all threads across the computer) or Monitor. Within the protected block of code, if the resource is a db connection, apply rule 1.
When using object locking, you should create your locks around an arbitrary object, not the current object's instance e.g.:

private static readonly object _lockObject = new object();

...

try {
    Monitor.Enter(_lockObject);
    // Do protected stuff...
}
finally {
    Monitor.Exit(_lockObject);
}


You do not need calloc() with fgets(), it adds nul terminator by itself: use malloc() instead. Also check for allocation errors and, maybe, use a meaningful name for Buffer (for example line).

char* line= malloc(MAXBUFLEN, sizeof(char));
if (line == NULL) {
    // Oops...
}

Also fopen() may fail then you should also check its return value:

if (fopen(...) == NULL) {
    // Oops
}

You should move the check for a line to ignore to a separate self-explicative function, that's why you felt the need to add a comment:

if (IsBlankOrComment(line))
    continue;

Implementing IsBlankOrComment() you should avoid hard-coded constants like 35, you should add #define and use a character instead of its ASCII code:

#define COMMENT_DELIMITER '#'

bool IsBlankOrComment(char* line) {
    char* trimmedLine = TrimWhiteSpaces(line);

    return trimmedLine[0] != '\0'
        && trimmedLine[0] != COMMENT_DELIMITER;
}

For a possible implementation you can read this SO post. Do not forget to include stdbool.h if you're using bool (instead of _Bool).

You now have to remove in-line comments, what's better than strchr()? No need to manually loop through the string:

char* inlineCommentStart = strchr(line, COMMENT_DELIMITER);
if (inlineCommentStart != NULL) {
    *inlineCommentStart = '\0';
}

Note that it also deals with line with leading and trailing spaces, if you do not need it then you definitely should go with Edward's lovely implementation (which uses strpbrk()).

To print the line (without comment) you then just need:

puts(line);

No need to print character-by-character while searching the delimiter (BTW do not use printf() when what you need to print is just a single character!) Also note that calling strlen() in a loop is (probably) extremely inefficient because, if compile can't determine that string is constant in the loop, it will emit code to call strlen() for each iteration.

Do not forget to close the file when you're finished:

fclose(stream);

And to free allocated memory:

free(line);

In this case you should ask yourself IF you need dynamically allocated memory. If MAXBUFSIZE is a preprocessor constant then you can directly declare a local variable (check also for stack size issues):

char line[MAXBUFSIZE];

If your application isn't multi-threaded and you call this function more than once you may want to also consider to make it static. Finally do not forget to add const here and there, where appropriate.


Exporting a table with header and subheader

I'm assuming the data in variable A is calculated somehow in MATLAB, and that you have a matrix A that you want on a tab-delimited format, with headers. If that's the case, then writetable is probably your best bet (as you have figured out).

The expressions below are very hard to scale, since 100 rows of data results in 100 rows of code.

C(3,:) = num2cell(A(1,:));
C(4,:) = num2cell(A(2,:));

Simply doing data_in_cells = num2cell(A) is much more robust and clean.

The following is probably the best way to achieve what you want:

A = [1,2,3;4,5,6];

headers = {'force', 'mass', 'acceleration'};
units = {{'N'},{'Kg'},{'m/s^2'}};   % or: units = num2cell(units);

table_of_data = cell2table([units; num2cell(A)]);
table_of_data.Properties.VariableNames = headers;

writetable(table_of_data,'tabledata.dat','Delimiter','\t')

The reason why I use a double nested cell for units is that when trying to create the matrix MATLAB checks if all elements in each column are of the same type, and if so concatenates them as that type. In MATLAB, [65 66, 'C'] becomes ABC, because it converts the entire array to chars.
Since the first column contains a single character N, this column looks like:

'N'
1
4

MATLAB translates this to: char([78; 1; 4]). 1 and 4 when converted to ASCII-characters becomes: "Start of heading", and "End of transmission". These are not printable ASCII. Placing N inside a cell will result in the correct result, since MATLAB can't concatenate a cell and integers.

Note that I'm not placing headers, units and the data in a single cell as you did (C). This is because:

You don't need that cell anywhere
Avoid the additional memory overhead


Convert list to a string with double quotes

create_list is building a list of all the items in the string form of data. And so you can change it to:

def create_list(data):
    return list(str(data))

I find it easier to read create_command if you merge some of the lines together:

def create_command(amount):
    command = ["START"] + create_list(amount) + ["STOP"]
    return str(command).replace("\'", "\"")

And so you can merge the above two changes together:

def create_command(amount):
    command = ["START"] + list(str(amount)) + ["STOP"]
    return str(command).replace("\'", "\"")

Expanding further, rather than using str.replace you can use json.dumps to format the list. This has the benefit that it will escape ' and " characters for you, which your code doesn't correctly handle. (Thanks Mathias)

import json

def create_command(amount):
    command = ["START"] + list(str(amount)) + ["STOP"]
    return json.dumps(command)


Horrible nested if statement for changing CSS based on RadioButton selection

You could use polymorphism to represent the states, and to apply the needed formatting.


Style

In C++, don't #include<stdio.h> or any other C-style .h file.  #include <iostream> should be sufficient for all of your I/O needs.  It is customary to put a space after #include.

In general, using namespace std is bad practice.  Here, you actually wasted more characters writing the "shortcut" than writing out std::cin and std::cout like you should have.

In the problem statement, the input is called t.  Why did you name your variable n in your code then?

x is a cryptic variable name.  I suggest countdown_init.

It is customary to end the output with a newline.  If you don't, then in Unix shells the command prompt would immediately follow the output on the same line, which looks ugly.

Algorithm

The reason your program exceeds the time limit is simple: this loop counts up to n, one step at a time.

for(long long i = 2; i <= n;i++)

Your algorithm is thus said to be O(t).

To speed it up, you need to fast-forward through entire countdown sequences.

#include <iostream>

int main() {
    long long countdown_init, t;
    std::cin >> t;
    for (countdown_init = 3; t > countdown_init; countdown_init *= 2) {
        t -= countdown_init;
    }
    std::cout << (countdown_init - t + 1) << '\n';
}

This solution would be O(log t), since it only loops once per countdown cycle.  We can estimate the amount of work by rounding up t to the last t of each cycle:

$$\begin{align}
t \approx&\ 3\ (\underbrace{1 + 2 + 4 + \ldots + 2^{c}}_{c\ \textrm{cycles}}) \\
  \approx&\ 3 \cdot 2^{c+1} \\
  =&\ 6 \cdot 2^c
\end{align}$$

The number of cycles \$c\$ is therefore

$$c \approx \log_2 \frac{t}{6} = O(\log t)$$


What is it for?
Without knowing what you would use this for I can only go by your question.
The behaviour of stc is not what the  question's title suggests as it is very easy to make it fail or behave in a non intuitive manner.
Forever pending
Consider the following use example
stc.sleep(1000, "test").then(()=>log("Test timeout");  // this promise is never resolved
setTimeout(()=>{
        stc.sleepProlong(2000, "test").this(()=>log("Test prolonged timeout")
    },200);

The first promise is left pending and will never be resolved.
Some other potential problems

Each time sleepProlong is called you leave another promise unresolved.
When sleepProlong is called the name implies that it "prolongs sleep", but if the sleep has already timeouted out it creates a new sleep???
If sleep is called with the same name as an existing sleep, the previous sleep can no longer be prolonged,
The stc interface exposes delayTimer making the state of stc untrustable.

Expectations?
From the question's title I would expect

that there is only one promise for a named sleep.
that the sleep and prolonged sleep can be canceled
that the sleep can be prolonged indefinitely
that attempting to prolong a sleep that has timeout does nothing.
that calling sleep with the name of an unresolved existing sleep does nothing

Some general style and coding points

Function argument names are inconsistent you call the timeout delay m in one function and ms in the other.
The line delete stc.delayTimer[name]; is not needed as you overwrite the value by calling sleep on the next line.
not using curlies {} to delimited statement blocks is a bad habit, Always delimit statement blocks with {...}.You had if (stc.delayTimer[name])  clearTimeout(stc.delayTimer[name]); is better as if (stc.delayTimer[name])  { clearTimeout(stc.delayTimer[name]); }
There is no need to check if the named timeout event handle exists. clearTimeout will ignore undefined and already timed out handles. Thus if (stc.delayTimer[name])  { clearTimeout(stc.delayTimer[name]); } can be clearTimeout(stc.delayTimer[name]); and not change the behaviour.
This may just be my personal preference but it feels wrong having the time m, or ms as the first argument. Putting the name first and then the delay seems more natural (and thus easier to remember)
You don't need to await the promise you return in the async function, Async functions do this automatically .
Ensure that you protect important state variables. If entries in the  object delayTimer are mutated then you lose the ability to maintain stc's correct behaviour. You can protect it via closure.

Cleanup and keeping original behaviour
without changing the behaviour of you code I have made changes as outlined in the above points, and modified some names.
const stc = (() => {
    const handles = {};
    return {
        sleep(name, time) { return new Promise(r => handles[name] = setTimeout(r, time)) },
        async prolong(name, time) {
            clearTimeout(handles[name]);
            return stc.sleep(name, time);
        }
    };
})();


Securely shuffling an array with 75 numbers in Go

Initialization

A simple loop would be easier to maintain than hard-coding an array of 75 values.

items := make([]int, 75, 75)
for i := range items {
    items[i] = i + 1
}

Seeding

The PRNG should be seeded just once.

You are correct that an Int64 seed is "only" capable of producing 264 ≈ 1019 distinct sequences, which is well under 75! ≈ 10109.

However, you should also consider the magnitude of the numbers involved.  The age of the Universe is well under 1018 seconds.  There is therefore no way you could remotely come close to producing a small fraction of the 75! possible permutations, just due to lack of time.  A 64-bit seed is more than enough to generate as many unreproducible sequences as you could ever want.

So, calling rand.Seed(time.Now().UnixNano()) just once in func init() will be sufficient.


AJAX alternative of using jQuery form UI

You can use jQuery's AJAX function for this directly and, you can pass object literals as parameters without using the form elements.

var params = {id : '1234'};
$.ajax({
  type: 'GET',
  url: url, // action attribute from form element
  data: JSON.stringify(params),
  contentType: 'application/json; charset=utf-8',
  dataType: 'json',
  success: function (result) {
      console.log(result);
  },
  error: errorFunc
});

Documentation can be found here.


Terrain map generator with JavaScript and HTML5/CSS

That map looks super cool! The performance isn't THAT bad, considering you're generating 2500 DIV elements :)

What you could do is generate one Canvas instead of so many DIVS. The GPU can render a canvas super-fast. That will also be helpful if you start adding more elements to your game.

There is no reason to use jQuery, so you can get rid of that too :)


One issue I see is you're using bind. bind creates a copy of the function but with a bound context. You appear to call it on each iteration, which will cause memory hogging, which causes the GC to kick in more often, thus lagging. You can simply just drop the use of bind and write your code without relying on context.

If you need to store state, store it somewhere else, like a single module holding your game state. It's also good to isolate state into one location instead of having it everywhere.

The render loop should just be a render loop. It should not be aware of anything else except a queue of things to do on each turn. On the other hand, the rest of the code shouldn't be aware of a render loop. All they need to do is to register operations to the queue, with only the assumption that the function they register gets executed per frame. This keeps code relatively decoupled with the scheduling mechanism.

In the following, we create a jobQueue which is just a list of things to do when the loop executes.

// The render loop is only aware of a job queue full of functions
const jobQueue = [];

function renderLoop(elapsed){
  requestAnimationFrame(renderLoop);

  // Consume tasks in jobQueue
  jobQueue.forEach( task => task.call(elapsed / (1000/60)) );
}

// Start the loop
renderLoop();

// All your code needs to do now is register
jobQueue.push(scale => { update some state });
jobQueue.push(scale => { render something });
jobQueue.push(scale => { check keyboard });

Also, it's best if you schedule the next frame prior to doing stuff. That way, anything that causes the loop to lag doesn't lag scheduling the next frame.

Another thing is timing. requestAnimationFrame's callback accepts 1 argument, a timestamp. Use that instead of Date.now. Now instead of using delta time (a time value) in your calculation, consider using a scale (a unit-less value). I've answered a similar review here. With delta time, you have to change your calculation to take in a time value. With a scale, you simply calculate output values, then multiply against the scale value. It's like a percentage value.

Lastly, the example above uses forEach for jobQueue. It's known to be slow. Feel free to replace it with a regular for or while loop.


What about taking advantage of the (stupid) fact that the context parameter inside a function invoked without call or apply will be the window?

mYApp.isWindow = function(obj) {
  if(!obj)
    return false
  return obj === (function() { return this})() //is this the window
     || obj.eval && obj.eval.call && obj.eval("this === (function(){ return this })()") //is that another window
     || false; //make undefined false
};

Seems to even work when wrapped in a with. That being said, you might have legitimate reasons to want to test for this but I can't think of any.

Edit: Added check for 'other' window. You could probably add some finagling to check that eval isn't a stub that always returns true. So if it returns true for example you could generate two random numbers, add them together, and then pass them into the eval string and have it add those numbers and confirm the result is indeed accurate. Let's be honest though, that's stupid, if someone wants to trick you that bad, they'll find a way.


C++ Calculate euclidean distance between tuples, for specified indices

Nice work! There's not much to improve here, but still:

Don't repeat yourself

You keep repeating the same type declaration over and over again. A simple type alias at the top of the function makes things so much cleaner:

using result_t = std::common_type_t<std::tuple_element_t<I, std::decay_t<decltype(ta)>>...>;

A little too trigger happy on the casts

I think this would be better without the final cast. std::sqrt() returns a double when passed integral types, and that's often desirable. Letting your users cast to an integer if they want after your function returns would be more flexible.

Prefer the namespaced version of C functions

std::sqrt is preferable over sqrt

Anonymous namespaces in headers mean almost nothing.

Your anonymous namespace may not generate a link-time symbol, but it still pollutes the global namespace for anything that includes it. sq() would probably be better off as a lambda inside of euclidean_distance() itself, or be in an actual named namespace.

Possible improvement:

It would be nice if this could be generalized to arbitrary norms. Passing functors that default to std::sqrt and sq would be really nice. Or perhaps a trait type that defines both the raising and the lowering operations in a single norm type might make sense.


Project Euler Problem #7 in Python (10001st prime number)

Upper bound for p_n

There is a known upper bound for the n-th prime.

It means that you don't need to guess how large it could be. upper_bound_for_p_n(10001) tells us in less than a micro-second that the desired number cannot be larger than 114320.

You just need to apply the Sieve of Erathosthenes up to 114320 and you're done:

from math import log, ceil

def find_primes(limit):
    nums = [True] * (limit + 1)
    nums[0] = nums[1] = False

    for (i, is_prime) in enumerate(nums):
        if is_prime:
            yield i
            for n in range(i * i, limit + 1, i):
                nums[n] = False

def upper_bound_for_p_n(n):
    if n < 6:
        return 100
    return ceil(n * (log(n) + log(log(n))))

def find_n_prime(n):
    primes = list(find_primes(upper_bound_for_p_n(n)))
    return primes[n - 1]

It calculates the 10001th prime in 15ms on my computer, compared to 35s for your code.


Just a couple of minor points:

In your constructor, you create an the array with an initial size of 4:

_items = new T[4];

However in your Clear method you set it to an size of 2:

_items = new T[2];

It's odd that you set it to a smaller number.  If you had a constant for initial size, or called Clear from the constructor this could be avoided.
That said, do you really want clear to discard _items?  If you're reusing the array in a similar section of code, it seems reasonable to assume that after Clear has been called, there is a good chance the the array would grow again to a similar size.  It may be more efficient to simply reset _size, but leave _items intact.  Obviously this depends how you're using the array as to whether or not it's a good idea...
You don't limit the size of the array.  Dynamic doubling whilst efficient, can get big pretty quick.  You might want to consider adding a maximum size to your array, again, this would depend on what you're using it for as to whether or not it's worth while.  List limits it's growth for example, albeit to a rather large number.


Responding to your question

  Is there a best practices way to [dispatch the getter via an interval]?

You could consider using requestAnimationFrame() (read more about using that with setInterval() in articles like this one) but that might be overkill since you are just updating a list.

Another option to consider is using websockets (presuming your server-side would support it). That way the client-side could be notified of updates to the list instead of having to request them periodically.

Bug in the sample code

The sample code shows these methods:

    created() {
        this.fetchFriendList()
        setInterval(this.fetchFriendList, 3000)
    },
    destroy() {
        clearInterval(this.fetchFriendList)
    },

However, clearInterval() takes an intervalID as a parameter, not a function reference.

  Parameters

  intervalID
  The identifier of the repeated action you want to cancel. This ID was returned by the corresponding call to setInterval().1

So instead of passing the method reference this.fetchFriendList, pass an identifier returned from the call to setInterval() in the created method.

1https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval#Parameters


Create monthly calendar with number of days and offset (day of week) as user input

First Welcome to Code Review, and nice first question for a beginner. You did
a good job with variable names, function names, comments and indentation,
although validInput = true; is incorrectly indented in both functions. The
function drawCalendar() is very inconsistent in the indentation.

Consider the User
You might want to add an error message such as
"Invalid input please enter a number between X and Y" with X being the lower
limit and Y being the upper limit.

DRY Principle
There is a software engineering principle call the Don't Repeat Yourself
principle that may apply to the two input functions. Well written functions
can be used in multiple places in code and decrease the amount of code
necessary to implement a program or library. This code count contain a
function called getInput() that implements most of getInputDays() and
a lot of getInputOffset()

int getInput(string inputPrompt, int lowerBound, int upperBound)
{
  int inputValue = 0;
  bool validInput = false; // used to verify input is valid
  while (validInput == false)
  {
    std::cout << inputPrompt << " : ";
    std::cin >> InputValue;
    if (inputValue >= lowerBound && inputValue <= upperBound)
    {
      validInput = true;
    }
    else
    {
      std::cout << "Invalid input, please enter a number between"
          << lowerBound << " and " << upperBound << "\n";
    }
  }
  return InputValue;
}

Reducing the amount of code is a benefit because it makes it easier to
write the code in the first place, modify the code later and debug the
code.

You did well following another software engineering called the Single
Responsibility Principle.
The single responsibility principle states that every module or class should
have responsibility over a single part of the functionality provided by the
software, and that responsibility should be entirely encapsulated by the
class. All its services should be narrowly aligned with that responsibility.

When raw numbers are included in code they can often be confusing. Also if
the same number is used multiple times in the code for the same reason,
such as for array bounds it is easier to understand the code and modify
the code using symbolic constants. Some examples that might apply to
this program

//Symbolic constants should be capitalized, multiple words separated
// by underscore.
constexpr int SHORT_MONTH = 28;
constexpr int LONG_MONTH = 31;
constexpr int SUNDAY = 6;
constexpr int MONDAY = 0;
constexpr int TUESDAY = 1;
constexpr int SPACES_IN_COLUMN = 4;

Switch Statement Versus if then else if
The function displayOffset() could be implemented in the following manner:

void displayOffset(int offset)
// used to create offset on the first line of calendar
{
  switch (offset == 1)
    case TUESDAY :
      std::cout << "       1";
      break;
    case WEDNESDAY :
      std::cout << "           1";
      break;
   ...
  }
}

This is somewhat more readable and maintainable that multiple if then else if
statements. It is much easier to add a new case than it is to add a new
else if statement.

Another alternative would be:

void displayOffset(int offset)
// used to create offset on the first line of calendar
{
  for (int i = 0; i < offset * SPACES_IN_COLUMN; i++)
  {
    std::count << " ";
  }
}

Complex Functions
It might be easier to understand, debug and modify the drawCalendar()
function if it was broken up into sub-functions following the Single
Responsibility Principle mentioned above.


My 2 cents:

Use jQuery toggleClass : http://api.jquery.com/toggleClass/
Use camelCase : currencycode -> currencyCode etc.
Use English everywhere : 'monnaie' should not be there
Booleans are awesome

        if($myCurrencycode == $initCurrencycode) {
            hasChanged = false;
            console.log(hasChanged);
        } else {
            hasChanged = true;
            console.log(hasChanged);
        }

  should be

   hasChanged = ($myCurrencycode != $initCurrencycode)
   console.log( hasChanged );

Finally,

if(!$menuDropdown.hasClass('hide')) {
  $menuDropdown.addClass('hide');
}

  can be replaced with $menuDropdown.addClass('hide');
  it will not add the class multiple times.


Recursively find files of certain types and log their paths (C++)

The declarations for dir and file can be moved lower, where they are first assigned values.  However, since dir is only used in one place, it can be eliminated and the value used directly.

HANDLE file = FindFirstFileW(root_slash.c_str(), &file_info);

When testing file attributes, the check for invalid attributes should be first, and you can combine several individual tests into one:

if (file_info.dwFileAttributes != INVALID_FILE_ATTRIBUTES &&
    !(file_info.dwFileAttributes & (FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_OFFLINE | FILE_ATTRIBUTE_SYSTEM) &&
    (name != L"." && name != L".."))

Since there are three attributes you want to ignore, you can define a constant to hold them rather than list them out in your if statement.

Incidentally, since cFileName is a C array, you need to assign it to a string variable to be able to use the equality comparisons with it.  Or you could leave it in cFileName and use basic comparisons like strcmp.  Since there are two similar strings that are very short, you could also do direct character comparison but that makes the code larger and harder to understand and should only be done when absolutely necessary.

Since you decrement limit with each recursive call to get_files, you reduce the limit for the current directory as well.  If your initial directory has 16 subdirectories, your search will skip the 10th, may skip some of the subdirectories of the first 9, and will search all of the directories under the 11th and later subdirectories.  You should use

get_files(path, ext, log, limit - 1);

instead.  If any of the recursive calls fail in some way (return nonzero) you ignore the error and keep going.  This is reasonable in this instance, but does make the "recursion limit reached" error somewhat pointless since it will never be returned to the caller.  This one value should probably be handled differently, so that if any search reaches the recursion limit, this value is returned to the original caller to indicate that the results are incomplete.

Potentially more serious is that your extension comparison is case sensitive.  A file called "IMAGE.JPG" will not be listed, because the extension ins in uppercase and you're looking for a lowercase one.

Unless there's an absolute need for it, you should omit the std::flush from the log outputs.  This will reduce the performance as every filename will be written one at a time, instead of in larger chunks.


Fetching and displaying the provisioning status of a phone number

You may want to use a different template for error messages. You can still reuse the overall design by inheriting from a base template.
You replace variable values a lot, making it hard to follow what the meaning of variables like num, number and strnumber are throughout the code. Instead write functions which create the various transformations of the input that you need, making your variables unchanged throughout the code. For example:

def format_number(number):
    return number.replace(" ","").replace('+91', '').strip()

Now you can get from number to strnumber without ever changing the former.
In some error cases you render the template with error set, but in at least one you use a different error message delivery: dnd_list.append("The number should contain 10 digits"). This seems inconsistent.
The various large branches of code should be moved into separate functions.
Single letter variables like e, r and j make this code hard to maintain. Yes, it's kinda obvious from context, but the less context you have to keep in your head while developing, the better.


I think the associative array approach is good. You could probably get away with:

for ($i = 0; $i < count($nodes); $i++)
  for ($j = 0; $j < count($nodes[$i]); $j++)
    $uniekenodes[$nodes[$i][$j]]++;

As incrementing NULL values results in 1.


My Thoughts

I haven't profiled any of these, but I'm going to assume speed is not a priority.

I like #2 the best.  It is clean and simple, and easy to understand what the code is doing at a glance.

I think #1 is ugly, and the sequential array slicing makes me nervous and seems easy to break.  If your number sizes change at some point in the future, this one would be the hardest to modify.

I think #3 is better, but not as clear or concise as #2.


Health Test App, It Returns a Score Based on the Answers Given

If you wish to keep your implementation scheme, I only have one large critique:

Names are important

Your naming scheme should allow a 3rd party to understand your code from a cursory glance. You have a lot of sneaky implementations tucked into your functions that aren't expressed in your naming convention.

All of your operations are stateful, which is technically ok but you use a lot of verbage that makes it sound like they're functional operations with actual return values. All of your functions act on stateful variables. Your naming convention should reflect this through the use of verb phrases, as opposed to nouns.

resetStorage: A good variable name. It is a verb that acts on localStorage

getStorage: Misleading. The traditional usage of the verb get is to retrieve a value or perform a computation (and return it). You are assigning this.healthScore. getStorage doesn't even have a return value. A more apt name would be something more like setHealthScoreFromLocalStorage.

toZero: What exactly is being set to zero? From the rest of your code (looking at resetStorage) I can infer that the value of 0 is the default value. It should be more along the lines of resetHealthScore or clearHealthScore.

returnMessage: It is updating this.message. So something more like updateHealthMessage?


Read and convert binary files to ASCII text

Aside from turning StringBuffer into StringBuilder, there are a few more things I'd like to note about your code.

Compound assignment operator

This line:

 lastString = lastString + line;

Can be rewritten as this one:

 lastString += line;

It's short and it complies with what many people would expect: a concatenation. By explicitly mentioning the original variable again, many people might think it is a different variable before looking at it more closely.

Additionally, you might also want to add a StringBuilder to the reading of the file. Even if the inputfile isn't that big, it would still be consistent.

Magic values

Consider this code:

for (int i = 0; i < lastString.length(); i += 8) {
     result.append((char) Integer.parseInt(lastString.substring(i, i + 8), 2));
}

Can someone other than the authro tell with certainty what the value 8 is? An educated guess would lead to the bit representation of 2 bytes, but we shouldn't have to guess that. Get rid of this so called "magic value" by adding a variable which clears it up:

int amountOfBits = 8;
for (int i = 0; i < lastString.length(); i += amountOfBits ) {
     result.append((char) Integer.parseInt(lastString.substring(i, i + amountOfBits ), 2));
}

Exception handling

You're completely bypassing exception handling. I'm assuming this is just so this contrived sample wouldn't get cluttered with code, but just in case it isn't:

throws Exception

is always a bad idea in an actual program. You should catch the exact exception and handle it appropriately.


Interesting question,

as far as I can tell, quicksort is recursive, your solution is not. Hence, your solution is not really quicksort.

Other than that, this makes me cringe:

  var pivotIndex = undefined;
  var low_Index = undefined;
  var high_Index = undefined;

  pivotIndex = inputArray.length - 1;
  low_Index = 0;
  high_Index = (inputArray.length > 2) ? (inputArray.length - 2) : 0;

just declaring a variable assigns the value undefined, there is no reason to assign it, so don't do it. Then right after you declared those variables, you assign values, which you could also do in the var statement. Finally, and this is truly a matter of tastes you could chain those statements:

  var pivotIndex = inputArray.length - 1,
      low_Index = 0,
      high_Index = (inputArray.length > 2) ? (inputArray.length - 2) : 0;

Even here, you could reflect on the repetition of inputArray.length and assign this to a shorter variable name, to make this more readable, and a fraction faster:

  var length = inputArray.length,
      pivotIndex = length - 1,
      low_Index = 0,
      high_Index = (length > 2) ? (length  - 2) : 0;

Then again, you are not using a consistent naming standard, always use lowerCamelCase in JavaScript. I think some professors dislike ternaries, I would avoid them in school or at least check with the professor.

  var length = inputArray.length,
      pivotIndex = length - 1,
      lowIndex = 0,
      highIndex = Math.max(length - 2, 0);

Other than that your white-spacing is far too generous, never use more than a double newline.

This probably also makes you loose points:

for(var low = low_Index; low < pivot_Index; low++){

I would use index instead of low, otherwise reading your code becomes too hard.

Finally, also check your code for repetition, you swap two entries a number of times, I would have written a dedicated function for that.


Optimizing O(m n) solution for longest common subsequence challenge

The algorithm is correct, but the implementation is sort of naive; it definitely doesn't scale to 50000-long strings. Even for the 1024-long strings it is very cache-unfriendly; most likely you spend most of the time in cache misses.

The wiki article mentions that

  dynamic programming approach only needs the current and previous
  columns of the matrix

Modify your code to run in a linear space. That shall give you a boost.


Initializing more than one instance object at a time in init method

A couple of thoughts:

You are conceiving the band as being something derived from the frequency. While this may be technically correct, from a user perspective, you generally choose a band and then choose a frequency within that band. So, I might have a model that reflects this:

typealias RadioFrequency = Decimal

enum RadioBand {
    case am
    case fm
}

extension RadioBand {
    var allowedRange: ClosedRange<RadioFrequency> {
        switch self {
        case .am: return 520.0 ... 1610.0
        case .fm: return 88.3 ... 107.9
        }
    }
}

struct RadioStation {
    let name: String
    let band: RadioBand
    let frequency: RadioFrequency

    init?(name: String, band: RadioBand, frequency: RadioFrequency) {
        guard band.allowedRange ~= frequency else { return nil }

        self.name = name
        self.band = band
        self.frequency = frequency
    }
}

and

guard let station = RadioStation(name: "KPCC", band: .fm, frequency: 89.3) else {
    // handle error here

    return
}

If you really wanted to compute the band from the frequency, you could do:

enum RadioBand: CaseIterable {
    case am
    case fm
}

extension RadioBand {
    var allowedRange: ClosedRange<RadioFrequency> {
        switch self {
        case .am: return 520.0 ... 1610.0
        case .fm: return 88.3 ... 107.9
        }
    }

    static func band(for frequency: RadioFrequency) -> RadioBand? {
        RadioBand.allCases.first { $0.allowedRange ~= frequency }
    }
}

struct RadioStation {
    let name: String
    let frequency: RadioFrequency
    var band: RadioBand? { RadioBand.band(for: frequency) }

    init?(name: String, frequency: RadioFrequency) {
        guard RadioBand.band(for: frequency) != nil else { return nil }

        self.name = name
        self.frequency = frequency
    }
}

Minor details in the above:

I wouldn’t generally subclass NSObject unless there was a compelling reason to do so.
Whether you make it a class or struct is up to you, but we often we would lean towards value types and immutable properties unless otherwise needed.
I’m abstracting the frequency ranges for bands out of the RadioStation type. This is behavior of radio bands, not of individual radio stations, themselves.
The radio bands might be better represented as an enumeration rather than an integer that has only two values, either 0 or 1.

In general, if you find yourself inserting comments to explain cryptic values (e.g. where you note that 1 represents “FM”), that’s a good sign that you should adopt an enumeration, which makes its intent clear.
Note, I made RadioFrequency to be Decimal, rather than Double. I did that because you really don’t need floating point math, but rather want to accurately represent decimal numbers.

FWIW, Double can introduce some strange behavior. Let’s say that you started at the lower bound of your AM frequencies and bumped it up by 0.1 ten times:

var value: Double = 520.0
for _ in 0 ..< 10 {
    value += 0.1
}

print(value, value == 521.0) // 521.0000000000002 false

The result is not 521. But, if you use Decimal, you get the expected behavior:

var value: Decimal = 520.0
for _ in 0 ..< 10 {
    value += 0.1
}

print(value, value == 521.0) // 521 true

See What Every Computer Scientist Should Know About Floating-Point Arithmetic.
I’d make the initializer failable in case the band didn’t match the frequency (or the band couldn’t be inferred from the supplied frequency).
I would not be inclined to have the RadioStation to have default values. That’s not a concept that makes sense. Sure, if you wanted your radio to default to a particular station, then fine, it would do that. But that’s not RadioStation behavior, but rather behavior of the radio.

You said:

  ... imagine if you wanted 8 such objects, this would just get very clunky.

If you had many, you might use collections. For example:

let stations: [RadioStation]

Or you might wrap it in a custom type that indicated the functional intent. For example, let’s imagine that your radio had programmable presets, then the model might be:

struct RadioPresets {
    var stations: [RadioStation]
}

It just depends upon what these various stations are for. But don’t shy away from simpler fundamental object types just because you might need multiple ones. If the concept of a single radio station makes sense (which it does, IMHO), then stick with a simple radio station object, and compose it into more complex objects/models as needed later.

But, as a generally programming principle, we generally prefer simple, cohesive types and compose complex objects from these simple objects (e.g. a collection of 8 radio stations).


Python process tracklist, get cumulative timestamp of each track

Implicit tuples

(tmm,tss) = (0,0)

This shouldn't need any parens.

Generator

  couldn't easily see how to rewrite it from a for-loop to a generator

It actually is quite easy. Make your code into a function, delete result, and replace result.append with yield.

Time spans

  are there better idioms for the (mm,ss) modulo-60 counters?

Yes!

Custom objects

  I think we don't need a custom object

Named tuples take one line to declare, and suck less than unstructured data. So do that, at least.

Underscores

I just noticed that you're looping with an underscore as your loop variable. By convention this means "I'm not going to use this value"... but then you used it anyway. Give this variable a meaningful name.

Example

import re
from collections import namedtuple
from datetime import timedelta

TRACK_PAT = re.compile(r'(?P<no>[0-9]+)\. (?P<name>.*) (?P<mm>[0-9]+):(?P<ss>[0-9]+)$', re.M)
Track = namedtuple('Track', ('number', 'time', 'length', 'name'))

def parse_track(body):
    t_total = timedelta()
    for match in TRACK_PAT.finditer(body):
        length = timedelta(minutes=int(match['mm']), seconds=int(match['ss']))
        yield Track(int(match['no']), t_total, length, match['name'])
        t_total += length

for track in parse_track(
"""
1. Waiting For A Miracle 5:02
2. Bedroom Eyes 5:01
3. In Over My Head 4:31
4. Higher Ground / Written-By – S. Wonder* 3:38
5. Hot Blood 4:15
6. Running Away 4:28
7. I've Had Enough 3:47
8. Blacklisted / Guitar [Other] – Jonny Fean* 4:11
9. Last Thing At Night 2:49"""
):
    print(f'{track.number} | {track.time} | {track.length} | {track.name}')


You really shouldn't use double for currency. It's probably fine for this, but in a real world application, the accuracy problems you'd experience would be terrible to deal with. It's recommended that you use the currency class for money.

Also, just a small note. I like your brace style, but most Java folks use a different convention. Consistency within a code base is most important, but folks get kind of crazy about this kind of trivial stuff. Best to do as the Romans when in Rome.

public Coin(double value){
    this.value = value;
}


Factory for arbitrarily high-order operations

Since this is tagged "functional-programming" I decided to take the functional approach. However, take note that Python isn't necessarily a "functional language," so it's not going to be as efficient as the iterative approach you were using. However, it looks like you're doing this from a theoretical standpoint, so you may find this interesting.

import functools

def iterate(f, x, n):
    """ Applies f n times to x. """
    if n == 0:
        return x
    else:
        return f(iterate(f, x, n - 1))

def iterate_for(f, x, n):
    """ Applies f n times to x, without recursion. """
    for _ in range(n):
        x = f(x)
    return x

def increase_order(f):
    return lambda x, n: iterate(functools.partial(f, x), x, n - 1)

def op_of_order(f, order):
    return iterate(increase_order, f, order)

def test():
    add = lambda x, y: x + y

    mul = increase_order(add)
    assert mul(3,5) == 15
    assert mul(7,3) == 21

    exp = increase_order(mul)
    assert exp(3,2) == 9
    assert exp(7,2) == 49

    tetract = op_of_order(add, 3)
    assert tetract(5,2) == 3125
    #assert tetract(7,2) == 823543
    #assert tetract(4,3) == 4294967296

if __name__ == "__main__":
    test()

The biggest change here was the abstraction of the loop you have in both increase_order and op_of_order into a function called iterate, inspired by Haskell's iterate function. I've provided both a recursive and non-recursive version for understanding and efficiency (Python has a no tail-call optimization) during testing.

In my opinion, both increase_order and op_of_order are much clearer when written this way, making it easier to see just what both functions actually do.


Finding sequential recurrences in a list of numbers

You're doing things the hard way.

dic = {}
for p1 in range(len(seq)):
    for p2 in range(p1+1,len(seq)):
        dic.setdefault(tuple(seq[p1:p2]), []).append((p1,p2))

For each range, you are calling .setdefault().  You should just use a default dictionary, which can automatically create a list for any unseen keys:

from collections import defaultdict

dic = defaultdict(list)

for p1 in range(len(seq)):
    for p2 in range(p1 + 1, len(seq)):
        dic[tuple(seq[p1:p2])].append((p1, p2))

Next, you're filtering the dictionary the hard way.

cleandic = {}
for key, value in dic.items():
    if len(value) > 1:
        cleandic.setdefault(key,value)

This can be expressed in one line, using list comprehension:

cleandic = { key: val for key, val in dic.items() if len(val) > 1 }

The next improvement comes from noting that the key portion of (-2, 3): [(0, 2), (2, 4)]} is completely recoverable from the value portion; using (0, 2) or (2, 4) as a slice of seq will return the appropriate sequence.  You do not need to maintain a dictionary; a list of lists is sufficient and less complex.  Instead of cleandic, you can have:

groups = [ val for val in dic.values() if len(val) > 1 ]

Instead of removing the second of these two dictionary values:

  #(1,4,-5,1,4,-5) : [(7,13),(10,16)]
     #(1,4,-5) : [(7,10),(10,13)]

You now just need to remove the second of these two list entries:

  [(7,13),(10,16)]
     [(7,10),(10,13)]

You can still sort this by noting that (7,13) represents a sequence of length 6.

groups = sorted(groups, key=lambda item: item[0][1] - item[0][0], reverse=True)

Any time you have to .copy() is good time to stop and think if there is another way to solve the problem.

    for key2, values2 in sorteddic.copy().items():
        ...
                  sorteddic[key2].pop(sorteddic[key2].index(value2))

Here, you are modifying sorteddic inside the loop, so you clearly can't loop on the sorteddic itself, which explains the need to copy the dictionary first.  Since the copy is itself in another loop, you are doing a lot of copies!

Moreover, this isn't even a loop!  It is just a way to extract the first item from the dictionary.

for key1, values1 in sorteddic.items():
    ...
    break

Rework the algorithm to not modify the container you're looping over:

def subset_of(long_groups, group):
    return any(lg[0] <= g[0] and g[1] <= lg[1] for long_group in long_groups
               for lg in long_group for g in group)

...

longest_groups = []
for group in groups:
    if not subset_of(longest_groups, group):
        longest_group.append(group)

Finally, you can rebuild your dictionary with the sequence tuples as keys:

readydic = { tuple(seq[group[0][0]:group[0][1]]): group for group in longest_groups }

Since all the dictionary copying has been removed, this should be significantly faster.


Data class where i need to set values for different fields at different times

Use Data Class which automatically generates field accessors, hashCode(), equals(), toString() and other methods. Read this for a quick introduction.

data class ABCDRequest (
    @JsonProperty("name")
    private var name: String? = null,
    @JsonProperty("question")
    private var question: String? = null,
    @JsonProperty("ans")
    private var ans: String? = null
)

For the official documentation on Data Class, head over to this link.


I linked to a very related question in a comment, and this will repeat some points from my answer to that other question. Still, there are some other things here.

Don't do stack.push(c). Do stack.push(symbolPosition + 1) instead. I.e. push the expected position, not the current character. When you just push the character, you have to call indexOf again later to get that character's symbol position when you pop it off of the stack. By just pushing the position to the stack to begin with, you avoid that. And by adding 1 when pushing it, you get a cleaner conditional, since you can just do stack.pop() !== symbolPosition
If you do the above, you don't need stack.length < 1 before the stack.pop() call either. Nothing will break if the stack's empty; pop() will just return undefined which won't match any symbol position, and thus trigger the return false.
I'd skip the isOpen variable. Sure, it might help explain what that modulo operation means, but you only need the result once. I'd rather put the explanation in a comment, and skip the single-use variable.
Similarly, I'd skip the c variable, which - if you follow the first point above - is also only used once (and whose single-letter name doesn't help explain much), and just do indexOf(str[i]).
I'd change the last line to return stack.length === 0 just to be explicit. Yes the result is the same, but the intent is clearer in my opinion. "Is the stack empty?" versus "Is the stack's length less than 1?". You could also do return !stack.length but that's unnecessarily cryptic.

In the end you get something like:

function isBalanced(str) {
    var stack = [];
    const allowedSymbols = '()[]<>';

    for(let i = 0, l = str.length; i < l; i++) {
        var symbolPosition = allowedSymbols.indexOf(str[i]);

        if(!~symbolPosition) {
            continue;
        }

        if(symbolPosition % 2 === 0) {
            stack.push(symbolPosition + 1);
        } else {
            if(stack.pop() !== symbolPosition) {
                return false;
            }
        }
    }

    return stack.length === 0;
}

As others have pointed out, you can do some tweaking with regard to const vs let vs var, but I'll leave that to you.


A1Notation conversion to row & column index

I see you fixed the index-checking/defaulting bug that gengkev pointed out in the comments. As SpiderPig mentioned the cleanest solution is probably index = index ? 1 : 0.

However, I don't know if I'd bother with the index parameter at all. So far, it's led to bugs, duplication across all three functions, and all it really does is add/subtract 1. That can be done anywhere.

So I'd recommend just translating to 1-based indices, and if you need zero-based indices, well, subtract 1.

I wouldn't worry about using a regex - but I'd probably make it stricter. I imagine that a cell reference isn't that flexible. I imagine the string may contain "$"s but that's about it. Correct me if I'm wrong.

However, cellA1ToIndex() also does too much. It checks things that the other two functions don't. So if you call the other two functions directly, your input isn't checked as strictly. For instance, colA1ToIndex() will accept a string like "%#", and return something wrong. Similarly, rowA1ToIndex() will gladly accept just about anything, and return NaN.

So I'd keep cellA1ToIndex as "dumb" as possible, and make sure the specialized functions are more robust.

Lastly, why a of maximum 2 letters for columns? Why not 3? Or 4?

I'd do something like this:

function cellA1ToIndex(cellA1) {
  var match = cellA1.match(/^\$?([A-Z]+)\$?(\d+)$/);

  if(!match) {
    throw new Error( "Invalid cell reference" );
  }

  return {
    row: rowA1ToIndex(match[2]),
    col: colA1ToIndex(match[1])
  };
}

function colA1ToIndex(colA1) {
  var i, l, chr,
      sum = 0,
      A = "A".charCodeAt(0),
      radix = "Z".charCodeAt(0) - A + 1;

  if(typeof colA1 !== 'string' || !/^[A-Z]+$/.test(colA1)) {
    throw new Error("Expected column label");
  }

  for(i = 0, l = colA1.length ; i < l ; i++) {
    chr = colA1.charCodeAt(i);
    sum = sum * radix + chr - A + 1
  }

  return sum;
}

function rowA1ToIndex(rowA1) {
  var index = parseInt(rowA1, 10)
  if(isNaN(index)) {
    throw new Error("Expected row number");
  }
  return index;
}


Lock free MPMC Ring buffer implementation in C

Did you test it?

I think you have a problem if a thread calls enqueue and is interrupted
just before the memcpy, having calculated pos to be slot-1.  If another
thread now calls enqueue and completes it will write to slot-2 and increment the pendingRead counter, leaving
slot-1 still unwritten.  If a third thread now reads before the first thread
can complete its write, the reader will read from the unwritten slot-1.  This
is becase the second thread correctly set the queue to say there is a pending
read (slot-2) but dequeue assumes the data must be in the next available
slot according to readPos.

A few other comments:

queue_t is defined (elsewhere) as a pointer type. I prefer pointers to be
explicit.
You have mixed use of struct queue * and queue_t
Return from malloc is not checked.
buf in struct queue should be void* not char **
Why are writePos and readPos of type uint64_t and not size_t?
After all, num is size_t.  Why the difference?
Loss of precision assigning num in createQueue


First, I like the explicit statement of the type signature. That's a good habit to get into, and makes it easier to capitalise on perhaps the greatest strength of using Haskell which is all the compile time checking. The provided signature is as general as it can be for lists.
Second, the single element base case is written cleanly and correctly.
The recursive case has room for a bit of picking apart. It is convention to use pattern matching syntax x:xs (or x1:x2:xs) for list recursive functions. As well as being cleaner to read, the behaviour is slightly different in that it can work out the first, second, and remainder of the list in a single pass without having to separately call !! twice and drop once.
foldl1' f (x1:x2:xs) = foldl1' f ((f x1 x2):xs)

One other improvement that I would suggest, taken directly from the prelude function by the same name, is explicitely handling the failure case when provided with an empty list. For comparison the inbuilt function produces an exception:

foldl1 (+) []
*** Exception: Prelude.foldl1: empty list


First things first.  Your variable names are not very well thought out.  Even after I decode it, cnt or count?? does not describe what it does.  I think a better name would be currentIndex.

Second, C# standards say to use camelCasing for variable names.  I would also read up on var, it is a very useful keyword for cleaning up code.

Third, brush should be a constant, if you follow my suggestion on the change to recursion, it should be made a class constant.

I also don't like that cnt is incremented outside of the loop.

Now onto the main question.

Just seeing if ((packet[objectstart] > 127) | (packet[objectstart]  < 127)) twice in the same structure (one inside the other one) is a huge code smell to me, especially when it is the same code inside the second, as it is the first.  This looks like a good case for recursion, a method calling itself.

It would go something like this:

private string ProcessSegment(int[] obj, int currentIndex, int objectStart, dynamic[] packet)
{
     if ((packet[objectstart] != 127) || currentIndex > Objectlength)
     {
         return string.Empty;
     }

     Console.WriteLine(packet[objectstart]);

     var bin2 = packet[objectstart] & brush;
     binR1 = Convert.ToString(bin2, 2).PadLeft(7, '0');

     obj[currentIndex] = Convert.ToInt16(packet[objectstart]);

     return binR1 + ProcessSegment(obj, currentIndex++, objectStart++, packet);
}

Your calling code will look something like:

obj[cnt] = Convert.ToInt16(packet[objectstart]);
objectstart++;

if (obj[cnt] >127)
{
    result += ProcessSegment(obj, cnt++, objectstart++, packet);
}

I have no way of testing this, but I think it should work.  Also note, please change the dynamic in the ProcessSegment call to be whatever the packet variable is


Wrapping IMemoryCache with SemaphoreSlim

Sorry this is a bit of a ramble, but a few things jump out at me:

17?!?! I don't have to tell you about magic numbers! This should probably be configurable... somehow...
Why is Locker static? It doesn't make sense to restrict access to one cache because a totally different cache is currently in use.
Locking the cache while you create an item isn't necessarily going to end well: it would be all too easy for create to try to access the cache, and now you have a deadlock. The 'easiest' way to resolve this would be to slightly abuse the cache, and instead of storing the values themselves store some wrapper which indicates whether the value is written yet with a different concurrency mechanism. This way, you can add a 'pending' value to the cache immediately, which can be initialised outside the lock.

This increases the complexity of dealing with create failures, because you have to communicate between threads with some other object, but now you can only dead-lock yourself by trying to access the object your are currently creating. It would be nice to detect this, but I think it might be impossible, so you probably want to give whatever mechanism awaits the pending entry a time-out. I don't think you can do better than this without passing the complexity off to the caller, which of course would ruin the nice API.

A better solution would probably be to provide a completely separate concurrency mechanism for handling 'pending' values, so that there is less overhead and complexity accessing the cache (presumably the more common operation). It wouldn't store the values, but rather just provide a mechanism to wait for them to appear in the proper cache (on a key-by-key basis).
I'd prefer that the cast to (T) was checked first, so that you can throw a highly-specific exception explaining that whatever was in the cache was not what the caller was expecting.
Since you are providing the access control, your class is probably also responsible for disposing the cache: it should provide this facility. Disposing Locker is also a concern. This adds to the opportunity for a consumer to get cryptic error messages if they are trying to access the cache as it is disposed.
Public APIs should have inline documentation (///), so that the maintainer knows what it's meant to do, and consumers can find out how to use them correctly without consulting the source-code.


Method for parsing floats and adding totals

The add method is overly complex for no real benefit. It is hitting a thumbtack with a sledge hammer. The add method is used for waaaay to much. It's not clear what it does. I had to spend 5 minutes dissecting what it did. For an 11 line method, that's pretty long.

I understand you are trying to DRY up your code, but you have sacrificed clarity for perceived duplication of code. Adding to the credit and debit totals appears to be duplicated code, when actually it is not. You are better off removing the add method and going for something explicit. What you do want to DRY up is the conversions of amount values to numbers, and perhaps some error checking.

Defining this inside your dateObject class makes ensuring arguments are numbers a quick one-liner.

var toNumber = function(x) {
    var n = Number(x);

    if (isNaN(n)) {
        throw new Error("Invalid number: " + amount);
    }

    return n;
};

Now, your addCredit and addDebit methods become explicit and easy to read:

this.addCredit = function(amount) {
    totals.totalCredit += toNumber(amount);
};

this.addDebit = function(amount) {
    totals.totalDebit += toNumber(amount);
};

The addLabel method flat out confused me for a good while because it delegated to the add method. As a general rule, avoid turning methods into a "utility belt" where they perform more than one task. It makes for confusing code that is hard to maintain and debug.

The addLabel method (as far as I can tell) becomes much easier to visualize and debug as well:

this.addLabel = function(label, amount, type) {
    var key = label + "-" + type;
    totals.labels[key] = totals.labels[key] || 0;
    total.labels[key] += toNumber(amount);
};

And now on to every programmers' favorite subject: naming things :)

You have a "class" called dateObject. Naming conventions in JavaScript dictate that "classes", or more accurately constructor functions, should capitalize their first letter. Secondly, your dateObject class does nothing at all with dates, and is confusing because JavaScript has a Date class. Crediting and debiting amounts has nothing to do with dates. I realize you omitted some code but consider renaming this class to something like Account:

function Account() {
    var totals = {
        totalDebit: 0,
        totalCredit: 0,
        labels: {}
    };

    var toNumber = function(x) {
        var n = Number(x);

        if (isNaN(n)) {
            throw new Error("Invalid number: " + amount);
        }

        return n;
    };

    this.addCredit = function(amount) {
        totals.totalCredit += toNumber(amount);
    };

    this.addDebit = function(amount) {
        totals.totalDebit += toNumber(amount);
    };

    this.addLabel = function(label, amount, type) {
        var key = label + "-" + type;
        totals.labels[key] = totals.labels[key] || 0;
        total.labels[key] += toNumber(amount);
    };
}


Exercise for ordering pizzas with user input

NumberFormat nf = NumberFormat.getCurrencyInstance();

Don't shorten names just because you can, it makes the code harder to read and maintain.
final double s = 8.0, l = 11.0, f = 14.0;

Perfect example of that. The more descriptive the names are, the better. Length should not be of any concern.

double toppingtotalprice =0;

A double is still a floating point. For money, you always want to use BigDecimal, or an int as the smallest unit your money has (Cents for example).

char ordermore = 'n';

Should mot likely be a boolean.

        //using a do while loop, because condition to stop is at the end.
        do{

You can use a while here, though.

I'll skip the rest of your code and directly skip to the part that you've been waiting for: That works, but is bad design.
Note that in the following examples I'm still using double for simplicity, you should use something else.
Let's start with the fact that you have a lot of repetition, extract common parts into a function which accepts parameters to parameterize it. For example:
private static final double inputPizza(double pizzaSizePrice, double toppingPricel) {
    System.out.println("Number of toppings?:");
    numberoftoppings = keyboard.nextInt();
    toppingtotalprice = (numberoftoppings * toppingPrice);
    System.out.println("Pizza Quantity:");
    pizzaquantity = keyboard.nextInt();
    return (pizzaquantity * toppingtotalprice * pizzaSizePrice);
}

That already reduces repetition a lot.
Now, we're going to encapsulate our information in a class of their own:
public class PizzaCosts {
    protected double price;
    protected double toppingPrice;

    public PizzaPriceValues(double price, double toppingPrice) {
        super();

        this.price = price;
        this.toppingPrice = toppingPrice;
    }

    public double getPrice() {
        return price;
    }

    public double getToppingPrice() {
        return toppingPrice;
    }
}

And in our main function:
PizzaCosts smallPizzaCosts = new PizzaCosts(8.0d, 1.0d);
PizzaCosts mediumPizzaCosts = new PizzaCosts(11.0d, 1.5d);
PizzaCosts largePizzaCosts = new PizzaCosts(14.0d, 2.d);

That groups the values nicely together and makes it easier to read. Now let's go one step further, we'll put them into a Map to access them dynamically based on user-input:
Map<String, PizzaCosts> pizzaCosts = new HashMap<>();
pizzaCosts.put("s", new PizzaCosts(8.0d, 1.0d));
pizzaCosts.put("m", new PizzaCosts(11.0d, 1.5d));
pizzaCosts.put("l", new PizzaCosts(14.0d, 2.0d));

PizzaCosts selectedPizzaCosts = pizzaCosts.get(keyboard.next());

if (selectedPizzaCosts != null) {
    runningTotal = runningTotal + inputPizza(pizzaCosts);
} else {
    // Invalid selection
}

Now that's a lot nicer, and should be enough to get you started further.


Leetcode #826. Most Profit Assigning Work solution in Java (Sort + Binary Search)

Algorithm

The algorithm is correct, but an optimization is possible.
When the input contains multiple jobs with the same difficulty,
then you can reduce the search space,
because at any difficulty level,
you're only interested in the most profitable job.
The time complexity would become \$ O(n \log n + w \log n')\$, where \$n'\$ is the number of unique difficulties.

Extract special treatment out of the loop

The loop in updateDifficultyAndMaxProfits has a special treatment for index 0.
Instead of evaluating a condition for each iteration of the loop,
since the input is guaranteed to have at least 1 element,
you could perform the special treatment before the loop begins,
and make the loop start from index 1, and no conditional.

Avoid modifying the input

You pass to the method updateDifficultyAndMaxProfits the difficulties array that was an input, and overwrite its content.
Although this saved you some space in memory,
it may not be acceptable, and not a good practice.
It would have been better to pass to the function a new array.

However, with the first tip at the top of this review,
this point will no longer matter,
because you will need a different approach to store the (difficulty, maxProfit) pairs that avoids redundant difficulty values,
and you won't know in advance the number of pairs you will need.
You may for example implement a computeDifficultyAndMaxProfits,
returning a list of pairs.

How about some streams and lambdas

Some elements of your program can be written more compactly with streams and lambdas, for example:

Job[] jobs = IntStream.range(0, profit.length)
    .mapToObj(i -> new Job(difficulty[i], profit[i]))
    .sorted(Comparator.comparingInt(job -> job.difficulty))
    .toArray(Job[]::new);

Since Job implements Comparable, the custom comparator is not necessary here.
Keeping the sorting logic outside the class like this is often more practical.
It's also compact to write.
If you needed to sort multiple times, you could store the lambda in a variable to avoid duplicating logic.

The final computation could also be written with streams and lambdas compactly:

return IntStream.of(workers)
    .map(w -> computeMaxProfit(w))
    .sum();


Use a single import

Instead of importing each individual class, I recommend importing the whole module with a short name. You can then use the short name as a prefix for all of your commands. It makes your code a bit more self-documenting, especially if you mix both tkinter and ttk in the same application.

For example:

import tkinter as tk
...
window = tk.Tk()
button = tk.Button(window, text="Start", command=askQuestion)

Separate widget creation from layout

In my experience, the layout of a GUI changes a lot more than the actual widgets, especially early in development. By separating widget creation from widget layout, it makes debugging much easier. It also makes it much easier to visualize the layout just by looking at the code.

Instead of this:

Label(view, text=self.question).pack()
Button(view, text=self.answers[0], command=lambda *args: self.check("A", view)).pack()
Button(view, text=self.answers[1], command=lambda *args: self.check("B", view)).pack()
Button(view, text=self.answers[2], command=lambda *args: self.check("C", view)).pack()
Button(view, text=self.answers[3], command=lambda *args: self.check("D", view)).pack()

... I recommend this:

label = Label(view, text=self.question)
button_a = Button(view, text=self.answers[0], command=lambda *args: self.check("A", view))
button_b = Button(view, text=self.answers[1], command=lambda *args: self.check("B", view))
button_c = Button(view, text=self.answers[2], command=lambda *args: self.check("C", view))
button_d = Button(view, text=self.answers[3], command=lambda *args: self.check("D", view))

label.pack()
button_a.pack()
button_b.pack()
button_c.pack()
button_d.pack()

Explicitly set side for pack

I recommend always explicitly setting the side for pack. Even though the default will likely never change, explicitly setting the side makes the code less ambiguous:

label.pack(side="top")
button_a.pack(side="top")
button_b.pack(side="top")
button_c.pack(side="top")
button_d.pack(side="top")


Choosing evenly distributed points from a million points on a sphere

Since we can assume all your points are on a sphere, there is a better way to compute distance than using the L2 Norm (Euclidean distance, which you're using).

If we transform your data points to Spherical coordinates, we could use a simple Manhattan distance on the theta and rho coordinates, which is less expensive to compute. Since you compute this distance about \$Nm\$ times (6 million points * 1000 sample points), I'm sure it would make a good performance difference.

Small note on the Spherical Coordinates :

Instead of having x,y,z coordinates, we use r, theta, rho, which correspond to :

r : the length of the vector
theta : angle on the XY plane
phi : angle of inclination starting from theta

So, to change data to spherical coordinates, we'd do the following (I assume data is arranged in a x,y,z manner). The conversion is very fast, but it could be further optimized if needed :

def convert_to_spherical(data):
    spherical_data = np.zeros_like(data)
    for i,d in enumerate(data):
        r = math.sqrt(d[0]**2 + d[1]**2 + d[2]**2)
        theta = math.acos(d[2] / r)
        phi = math.atan(d[1] / d[0])

        spherical_data[i] = np.array([r, theta, phi])

    return spherical_data

Then, you could use this instead of data and change the metric used by pairwise_distances to manhattan. You'll need to dig a little bit to understand why this works, but consider that since the parameter r is always the same, you can simply compute the difference between the angles.

Since my laptop is pretty bad, I couldn't generate data to sample 1000 points out of 1000000. These times were generated sampling 300 points from 100000 points, I started timing after generating the points but I included the coordinates transformation in the times :

Time using your optimized solution : 213.1844208240509s
Time using the spherical coordinates : 140.83173203468323s

Considering this pretty big time difference, I'm pretty sure performance would be much better on your data sample.

If afterwards, you need to get your coordinates back to the cartesian plane, the formula is pretty easy and you can find it online easily.

I've generated the points using thanks to this answer :

def sample_spherical(npoints, ndim=3):
    vec = numpy.random.randn(ndim, npoints)
    vec /= numpy.linalg.norm(vec, axis=0)
    return numpy.transpose(vec)


Dirty but Efficient Texture Atlas in Spritekit

Just some quick minor complaints...

If braces are absolutely necessary in a switch, there's no reason why they shouldn't also be Egyptian-style like everywhere else in your code:

case BlockTypeDirt: {
    int amount = (type * numImagesEach) + damageLevel;
    return _tilesFromAtlas[amount];
}

But this seems unnecessary altogether.  We can refactor the switch statement as such:

switch(type) {
    case BlockTypeDirt:
    case BlockTypeRock:
        return _tilesFromAtlas[(type * numImagesEach) + damageLevel];
    default:
        return nil;
}

Now, I'm not sure I actually particularly like cramming all that inside the brackets, and the extra variable doesn't hurt, so we could keep it in the switch, but still, let's combine these cases and fix our brackets:

switch(type) {
    case BlockTypeDirt:
    case BlockTypeRock: {
        int amount = (type * numImagesEach) + damageLevel;
        return _tilesFromAtlas[amount];
    }
    default:
        return nil;
}

Our code has some borderline magic numbers:

int numFormats = 3;

int numImagesEach = 4;

I'll deal with the latter first.  It's defined as the first line of a function, it's only used within the function, and it's used as a constant.

static int const kNumberOfImagesEach = 4;

The other variable is a little hard to say.  It may be that it's simply out of context, and in reality, might be different values, as this number is passed into the function that actually uses it.  I'll let you use your best judgment on that one, but you should think about it.

int numImages = (int)atlas.textureNames.count;

This is an example of why I default to NSInteger rather than int in all of my Objective-C code--that's what Apple has defaulted to, and I'd rather not have to cast all of my returns from Apple's methods, which you'll probably find that on balance, you're using Apple methods more than any other single developer's methods.


Mapping yielding lots of warnings in use

You have a bug

This doesn't compile for me:

hm->[index] = k;
hm->[index] = v;

I think you meant this:

hm->k[index] = k;
hm->v[index] = v;

Understanding the warnings and responding to them

  Recently, I wrote a C header file that defines a new type called HashMap that allows for the storage of key/value pairs.

As comments pointed out, this is not a hash map. It's a map. This wiki page explains what is a hash map.

  I am just learning about the wonders of void pointers and as I use them, I get lots and lots of warnings about making pointers without a cast.

Pay attention to the warnings.
Any unhandled warnings are bugs waiting to happen.

Since you mentioned you're new with pointers,
I'm getting the feeling that maybe you're just not comfortable reading warnings yet.
They are not that hard to read though,
and you don't really have a choice:
you must read and understand them so you could eliminate them.

Here's an example:

t.c: In function 'main':
t.c:31:5: warning: passing argument 2 of 'hashmap_push' makes pointer from integer without a cast [enabled by default]
     hashmap_push(&hm, 3, 7, 0);
     ^

As a reminder, here's the method signature:

void hashmap_push(HashMap *hm, void *k, void *v, int index);

The method takes as 2nd parameter a void*,
but you're passing it the int value 3.
Well, that just doesn't work: you're passing the wrong type.
To make it work,
the compiler casts this integer to void*,
and warns you about it.
Is this really what you wanted?
No. Casting an int variable to void* can't be good.

The next warning is related to the first:

t.c:15:6: note: expected 'void *' but argument is of type 'int'
 void hashmap_push(HashMap *hm, void *k, void *v, int index) {
      ^

The first warning was about calling hashmap_push with the wrong parameter types,
this one is about the hashmap_push receiving the wrong parameter types.

Next warnings:

t.c:31:5: warning: passing argument 3 of 'hashmap_push' makes pointer from integer without a cast [enabled by default]
     hashmap_push(&hm, 3, 7, 0);
     ^
t.c:15:6: note: expected 'void *' but argument is of type 'int'
 void hashmap_push(HashMap *hm, void *k, void *v, int index) {
      ^

I hope you guessed, this warning is about the same line,
but this time argument 3, which is the int value 7.
Same problem: casting an int to void*.

t.c:33:5: warning: passing argument 2 of 'hashmap_get' makes pointer from integer without a cast [enabled by default]
     int v = (int)hashmap_get(&hm, 3);
     ^
t.c:20:7: note: expected 'void *' but argument is of type 'int'
 void *hashmap_get(HashMap *hm, void *k) {
       ^

Based on the explanations earlier,
can you tell what this is trying to tell you?

   The 2nd argument of the call to hashmap_get is invalid, as the
 number 3 is of type int instead of void*. The warning after that
 is about the receiving side: the hashmap_get is expecting a void*
 but it's receiving an int.

Finally, this one:

t.c:33:13: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
     int v = (int)hashmap_get(&hm, 3);
             ^

Can you tell what the warning is trying to tell you?

   The hashmap_get method returns a void*, but you're casting it to
 int. This is not valid.

In short,
all these warnings were trying to tell you that you're calling methods with the wrong types.
It's a fairly lucky accident that this code works at all and produces the expected output.
Without clearing up these warnings by calling the methods with the appropriate types,
you cannot trust this code.

  The header file itself does not yield any warnings, but when I use the header file, I get lots.

When the header file compiles without warnings,
but the source file using that header produces warnings,
that practically means the source file is misusing the header.
The header is like a contract:
it specifies what you can do.
Your source file twisted that contract.
You got a result that sort of magically seemed to work,
but it's in violation of the contract,
and it wasn't really supposed to work.

Using the map without warnings

This (by no means good) code eliminates the warnings and works:

int main(map) {
    HashMap hm;
    hashmap_init(&hm, 10);

    int key = 3;
    int value = 7;
    hashmap_push(&hm, &key, &value, 0);

    int v = * (int*) hashmap_get(&hm, &key);

    int key2 = 3;
    float value2 = 5.3;
    hashmap_push(&hm, &key2, &value2, 0);

    float v2 = * (float*) hashmap_get(&hm, &key2);

    printf("%d\n", v);
    printf("%f\n", v2);

    return 0;
}

This code passes the methods the types they expect,
and doesn't make invalid casts, namely:

&key is a int*, which is a subtype of void*, therefore valid
Same for &value
Casting the 1st call to hashmap_get to int* is valid, because it corresponds to the type of &value that was passed in earlier for &key
Casting the 2nd call to hashmap_get to float* is valid, because it corresponds to the type of &value2 that was passed in earlier for &key2

I used different value types for the sake of a demonstration,
but keep in mind that ideally (and in 99% of practical cases) all values of a map should be of the same type.
Among other things,
one reason for that is given some key k whose value you don't know,
you cannot know in advance the correct type of the value.
In this specific example, I knew in advance that the value of key2 is value2.

Finally, what do you think the program outputs?

       7
     5.300000

Well, this is a bit unexpected from a map.
Normally I would expect from a map that if I set the value of key 3 to x,
and then again set the value of key 3 to y,
the second call would update the existing entry and overwrite it with y.
This map works this way because of this code in hashmap_get:

    if (hm->k[i] == k)
        return hm->v[i];

That is, you are comparing the pointers of keys, rather than their values.
In a more common map implementation,
two distinct key objects both having the value 3 would be treated as the same key.
To make this code work that way,
it will take a substantial rewrite,
and rethinking of the types.

Other coding style issues

I suggest to use braces with all single-line statements, for example instead of:

for (i = 0; i < hm->size; i++)
    if (hm->k[i] == k)
        return hm->v[i];

Write like this:

for (i = 0; i < hm->size; i++) {
    if (hm->k[i] == k) {
        return hm->v[i];
    }
}

It's a bit longer, but it can save you from some simple but common mistakes.