Manipulating CSV files to regular text file

Use with when dealing with files.

There are great benefits discussed in the docs. Summarizing it handles closing and exceptions automatically. It makes it possible to write shorter code: look Andrey's answer for a rewrite.

Miscellaneous

Drop my from the start of your variables' names.
Learn list comprehension because it is extremely powerful, here I give you an example:

:

with open(csv_file) as input_file:
    lines = [line.split(",", 2) for line in input_file.readlines()]
    text_list = [" ".join(line) for line in lines]


Overall, it's pretty good. My comments are:

Use do/end for multiline blocks.
Typical Ruby style is a 2-space indent.
I think @thesaurus.drop(1) looks a bit better than @thesaurus.slice(1..-1)
match is not a good local variable name, word is more descriptive
Template is too complicated: you can just use multiple %s placeholders with an array of Strings.

I'm not commenting too much on the algorithm, since you weren't asking, but it seems a bit complicated. I'd be tempted to try simplifying it a bit.

Here's your code with the above changes applied:

dict = {
  'hello' => ['hey', 'what\'s up'],
  'name' => ['nomenclature', 'epithet'],
}

str = 'hello, my name is'

class SentenceMaker
  def initialize str, dict
    @thesaurus = []
    @template = str.gsub(/\w+/) do |word|
      if (dict[word])
        @thesaurus.push dict[word]
        '%s'
      else
        word
      end
    end
  end

  def each
    @thesaurus.first.product(*@thesaurus.drop(1)).each do |repl|
      yield @template % repl
    end
  end
end

SentenceMaker.new(str, dict).each {|sentence|
  puts sentence
}


I think the clearest way to approach this would be to define all the array items up front, to separate out the somewhat convoluted data boilerplate from the branch logic. Also, every query contains project at the end, so to decrease repetitiveness (and to increase the distinction between the different branches later), you might make a function for it.
function setQuery(key, select) {
  // Not sure what these should be called, there's probably a more precise name than `matchers`
  const matchers = {
    project: {$project:{_id:0, quote:1} },
    sample: {$sample:{size:5}},
    any: {$match:{quote:{$ne:null}}},
    text: { $match:{quote:{ $regex: new RegExp(key, 'i') } }},
  };
  const makeProjectQuery = (...initials) => [...initials, matchers.project];

  if (key === "-") {
    return makeProjectQuery(select === "sample" ? matchers.sample : matchers.any);
  } else {
    // Then key is a word; search for it
    return select === "sample"
      ? makeProjectQuery(matchers.text, matchers.sample)
      : makeProjectQuery(matchers.text);
  }
}

It's a few more lines, but I think it's easier to make sense of at a glance. Plus, if you ever needed to expand the functionality of this section, it would be a pretty natural extension to add something to matchers and add conditions for it in the lower body.
The code could be further condensed, but it would come at the sake of readability.
Review
Some suggestions regarding your original code:
Only quote property names when necessary - leaving out the "s results in less syntax noise and is a bit easier to read and write.
Indent code properly - two statements that are at the same level in a block should have the same indentation level - this makes the control flow clearer. Similarly, when ending a block, consider putting the } on the next line - being able to pick up on the locations where blocks begin and end at a glance is very important. Lots of IDEs can automatically indent code for you, they're well worth it.
Consider using spaces around operators, especially in complicated code. select === "sample" is easier to recognize at a glance than select==="sample" (especially if more operators become involved later)
When one branch differs from another only in a single expression, consider the conditional operator instead of repeating everything else around the expression. (eg, replace with something like select === "sample" ? matchers.sample : matchers.any as above) You don't have to use the conditional operator - sometimes it's clearer without it - but it's something to think about in that sort of situation.
Good comments use natural language that flows while reading the code out loud.


Unnecessary else:

    if length <= 1:
        return arr

    else:
        pivot = arr.pop()

    ...

If the first path is taken, the method exits.  If the second path is taken, then execution continues with the remainder of the method.  So you could write the rest of the method inside the else: clause:

    if length <= 1:
        return arr

    else:
        pivot = arr.pop()

        ...  # Now part of the else statement

Or, for more "left leaning" code, remove the else: clause altogether:

    if length <= 1:
        return arr

    pivot = arr.pop()

    ...

Loop like a native

    items_greater = []
    items_lower = []

    for item in arr:
        if item > pivot:
            items_greater.append(item)
        else:
            items_lower.append(item)

Here, you are creating a list, and then calling .append() to repeatedly add items to that list in a loop.  Python has a builtin mechanism to do this, faster.  List comprehension:

    items_greater = [item for item in arr if item > pivot]
    items_lower = [item for item in arr if not(item > pivot)]

Why not(item > pivot), and not simply item <= pivot?  For the most part, the latter will work.  But there are gotchas and special cases.  If there are infinities (+Inf, -Inf) or a not-a-numbers (NaN) in the list, items might be omitted from both lists.  For example, if the list contains a NaN, both NaN > 10 and NaN <= 10 are False, which would result in that item not being added to either the items_greater or the items_lower lists!  Worse, if pivot happened to become NaN, then all arr items would be excluded!  Similarly, if there are two infinities in the list, both +Inf > +Inf and +Inf <= +Inf are False.

PEP-8

The PEP-8 coding standard has many suggestion about how to format code.  Binary operators, for example, should have a single space on either side of the binary operator.

    return quick_sort(items_lower)+[pivot]+quick_sort(items_greater)

should be:

    return quick_sort(items_lower) + [pivot] + quick_sort(items_greater)


@Ethan's review already mentioned the basic improvements, but I think that there are other things you could improve and experiment with. At the end of this review I've put together a working example of the refactored code, so you can refer to it for all the things I'm mentioning.

A few other nits...

When your program consists of a single source file, you might as well avoid declaring function prototypes and put the other functions above main. This will ease maintenance, since it is one less place to update if you change a function name/parameter type.
Instead of passing a fixed char array to getline and limiting yourself to 80 chars max, you can pass a std::string to it and allow for arbitrary length words.
Make sure to pass the string parameter of gameScore as a const reference. In C++, when you pass an object to a function, it will be copied unless stated otherwise. So in that case, gameScore is seeing its own copy of the word. But you don't need to pay for that copy since the function is only inspecting each character of the string, without modifying it. Enter references. When passing a read-only reference, also make it const (check the example at the end for the details). It is important to note though that this tip applies to objects only (classes, structs. std::string is a class, mind you). Native types like integers and pointers are actually better if passed by value, since the hardware has registers to store them, so copying an int into a function is free.
You did right by storing the length of the string in a local variable inside gameScore to avoid calling the method in a loop, but it is actually not a 100% right. Being pedantic, string.length() returns an unsigned integer type. You have a few options here to match the type: C++11 and above, use auto and let the compiler infer the exact type. Older C++, you can use std::string::size_type (if you really love typing ;)) or shorter, a std::size_t, which is equivalent. The only real implication of using int like you currently do is that on some platforms it might be smaller than the size of the type returned by string, so assuming we are dealing with a Gigabytes long string, it could theoretically truncate the value and loose part of the string's length. Not the case with your program, I'm sure, but it is good to be aware of this when writing portable code.
Use const on local variables that are only assigned/initialized once. For instance, that int score. When the scope of a variable is small, it makes little difference, but it is good to get in the habit of using it. When looking at a 100 lines long function, you will be happy to know that the variables you are tracking are not going to be changed after they are declared.

An alternate implementation for letterValue:

I didn't really like that switch in letterValue. It is not hard to understand nor unclear, but it just feels too long and verbose...

You could use a Standard map to shorten things up a bit. Map each lower case letter to its integer value, them just lookup the map. If you cast each letter tolower before looking up the map, you don't have to repeat every char for upper and lower case.

Sample implementation:

#include <iostream>
#include <cctype>
#include <string>
#include <map>

int letterValue(char ch)
{
    // This map replaces your switch/case.
    // The upside is that you don't have to specify
    // upper and lower case letters. The downside is
    // that the letter values have to be repeated
    // for each entry.
    //
    // Notice that we made it a static constant, so the map
    // doesn't get recreated every time we enter the function.
    //
    // NOTE: To compile this code, you'll need to
    // make sure C++11 support is enabled in your
    // compiler (should be fine by default with recent
    // versions of Visual Studio).
    //
    // Also notice that your solution is missing the entry
    // for 'n', as was pointed out by Edward in his answer.
    //
    static const std::map<char, int> charValues = {
        {'a',1}, {'e',1}, {'i',1}, {'l',1}, {'o',1},
        {'r',1}, {'s',1}, {'t',1}, {'u',1}, {'n',1},
        {'d',2}, {'g',2}, {'b',3}, {'c',3}, {'m',3},
        {'p',3}, {'f',4}, {'h',4}, {'v',4}, {'w',4},
        {'y',4}, {'k',5}, {'j',8}, {'x',8}, {'q',10},
        {'z',10}
    };

    // Since you want to return 0 for a non-mapped letter
    // we first find() it, then check the result. The `? :`
    // thingy is the ternary operator, in case you are not
    // familiar with it. It's just like a compact version
    // of an if then else...
    //
    auto iter = charValues.find(std::tolower(ch));
    return (iter != std::end(charValues)) ? iter->second : 0;
}

int gameScore(const std::string & word) // <= Here you can see the const
         // reference, to avoid copying the string. The `&` means reference.
{
    // Notice the const here to enforce one-time initialization.
    const std::size_t length = word.length();

    int total = 0;
    for (std::size_t i = 0; i < length; i++)
    {
        total += letterValue(word[i]);
    }

    return total;
}

int main()
{
    while (true)
    {
        // Using a string instead of a fixed size array.
        std::string word;
        std::cout << "Enter a word: ";
        std::getline(std::cin, word);

        // std::string has this handy method to test if it is... Empty!
        if (word.empty())
        {
            break;
        }

        const int score = gameScore(word);
        std::cout << "The score for '" << word << "' is " << score << "\n";
    }

    std::cin.get();
}


Singly Linked List "Strange sorting" exercise

Interesting exercise.

I think you missed an easy solution to it which I'll get to, but a code-review first...

Vertical whitespace is a critical part of the readability of code... and you are missing a lot of it. Code like:

    if (t.next==null){break;}
    t.next = t.next.next;
    if (s.next ==null){break;}
    s.next = s.next.next;
}
if (t==null){t=heade;}
else if (t.next==null){t.next = heade;}

should be:

        if (t.next==null) {
            break;
        }
        t.next = t.next.next;
        if (s.next ==null) {
            break;
        }
        s.next = s.next.next;
    }
    if (t==null) {
        t=heade;
    } else if (t.next==null) {
        t.next = heade;
    }

and ...

static class Node
{
    int val; Node next;
    Node(int v){val=v;}
}

should be:

static class Node {
    int val;
    Node next;
    Node(int v) {
        val=v;
    }
}

Note that the community consensus for code style in Java is that {} braces should be opening at the end of the line, not the start of the next. I understand if your local work environment may have different "rules", but you should be aware that it is different to common Java style.

Your variable names are awkward. Things like "uneven" are not the opposite of "even" in this case, the opposite is "odd". Also, s and t are variables that I could not "imagine" what they are short for. If a 1-letter variable name is not special, it should at least make some sense... i is for index, use x and y in coordinate type variables, use p for position, or something.... but in your context t=headu, s=heade and I cannot think of something that s and t could mean.

Your main method, and the way it accepts the argument for the "size" of the test list, confused me a bit. I had to figure out the format of the input, etc. and how to make it run. You should comment things like that.

Now, about your algorithm.... it is not bad, it essentially builds two lists, and appends the one to the other, but I am concerned about the exit conditions of the loop... you have multiple of them (the for-loop conditions, and then multiple break conditions with "recovery" after the loop.

This is because you are tracking multiple pointers through the source list.

If you just iterate with one pointer in the source list, and have conditional code inside the loop, it's cleaner.

public static void strangerSort(Node list) {
    if (list == null || list.next == null) {
        // already stranger sorted.
        return;
    }

    Node eventail = list;
    Node oddhead = list.next;
    Node oddtail = oddhead;
    boolean even = false;
    // start from 3rd item in list
    // (guard condition guarantees at least 2 nodes)
    Node next = oddtail.next;
    while (next != null) {
        Node n = next;
        next = next.next;
        even = !even;
        if (even) {
            eventail.next = n;
            eventail = n;
        } else {
            oddtail.next = n;
            oddtail = n;
        }
    }
    eventail.next = oddhead;
    oddtail.next = null;
}


You could separate your I/O from the pure code:

fizzBuzz :: Int -> String
fizzBuzz n | mod n 3 == 0 && mod n 5 == 0 = "FizzBuzz"
           | mod n 5 == 0                 = "Buzz"
           | mod n 3 == 0                 = "Fizz"
           | otherwise                    = show n

main = mapM print (map fizzBuzz [0..100])


Instead of joining the data of two tables in Python, you should une an SQL join query to ask the database do the work for you.

You also should not inject parameters directly into the query and let the driver do it for you by means of parametrized queries.

Lastly, a list-comprehension is better suited to build your output than using append.

Proposed improvements:

def get_logs_messages(request_id, destination=None):
    parameters = (request_id,)
    query = (
        'SELECT logs.modified_dt, logs.message '
        'FROM scripts_deployment_logs AS logs '
        'LEFT JOIN deployment ON logs.deployment_id = deployment.deployment_id '
        'WHERE deployment.request_id = %s'
    )

    if destination is not None:
        query += ' AND deployment.destination = %s'
        parameters = (request_id, destination)

    conn = MySQLdb.connect(**dbconfig)
    cursor = conn.cursor()
    cursor.execute(query, parameters)
    messages = [
        '{}: {}'.format(dt, message)
        for dt, message in cursor.fetchall()
    ]
    cursor.close()
    return messages


Using a mechanical refactoring approach, you could create an array of objects to encapsulate the offsets and values associated with each offset:
movement(_b) {
  let centerOfPaddle = this.y + this.height / 2;

  let offsets = [
    { offset: 80, value: 4 },
    { offset: 60, value: 2 },
    { offset: 40, value: 1 },
    { offset: 20, value: 0.5 },
  ];

  for (const { offset, value } of offsets) {
    if (centerOfPaddle < _b.y - offset) {
      this.y += value;
      break;
    } else if (centerOfPaddle > _b.y + offset) {
      this.y -= value;
      break;
    }
  }
}

Going further, you could do a more conceptual refactoring and figure out the math behind your logic. For example:
movement(_b) {
  let centerOfPaddle = this.y + this.height / 2;

  for (let i = 80, j = 4; i >= 20; i -= 20, j /= 2) {
    if (centerOfPaddle < _b.y - i) {
      this.y += j;
      break;
    } else if (centerOfPaddle > _b.y + i) {
      this.y -= j;
      break;
    }
  }
}

You could give those loop variables more appropriate names like offset and value.


few things that come to mind on a quick look:

You might consider naming this something other than "Copyinfo".  If it is archiving transactions, for example, you might name it "ArchiveTransactions".  If you do decide to stick with the name, you should go with the Pascal Case version: "CopyInfo".  While you're at it: it's always good to specify public instead of leaving it implicit.

You don't need to do Sheet2.Range("A2").Rows("2:2"), you can also do Sheet2.Range("2:2") or just Sheet2.Rows("2:2"), or (and most simply) Sheet2.Rows(2).  I like putting things in With blocks (although many people won't for just two things) because I like reducing code duplication.

As for the syntax with the If statement... If there is an Else, it should be on multiple lines, in my opinion.  The way you had it above with the line continuation seems to go out of it's way to stay on one line (which, it doesn't anyway!).  Clarity always wins over conciseness on my book.

If you use Application.ScreenUpdating as shown below, it will eliminate the screen flicker that can happen when you switch sheets, as well as speed up the performance (which, since this Sub doesn't do a whole lot, performance tuning isn't necessary).

Public Sub Copyinfo()

    Application.ScreenUpdating = False

    On Error GoTo Err_Execute

    Sheet1.Range("A17:R17").Copy

    With Sheet2.Rows(2)
        .Insert shift:=xlDown
        .PasteSpecial Paste:=xlPasteValuesAndNumberFormats
    End With

    Sheet1.Range("C5:I16, Q5:R5").ClearContents

Err_Execute:
    If Err.Number = 0 Then
        MsgBox "Copied Data", vbInformation
    Else
        MsgBox Err.Description
    End If

    ThisWorkbook.RefreshAll
    ThisWorkbook.Save

    Application.ScreenUpdating = True

End Sub


As far as I'm aware, CodeReview is for completed programs. I imagine that this question would be better suited in StackOverflow. That being said, I see no point in duping the question on a different site.

Without seeing the rest of the program, and solely in a time interest, I'd say you keep the change function and ignore the validations. If you want a form field to be required, you can add 'required' to the input.

<form>
  <input type="text" name="input1" value={this.state.input1} onChange={e => this.change(e)} required />
</form>

You can find more on the MDN web docs for the required attribute.

Side note: you can also bind this.change as this.change = this.change.bind(this) in the constructor if you intend on using it for multiple fields. It'll save you some bytes, but if it's just a one off, binding it in the element itself like you have should be fine.


Putting rows of ascending digits and eliminate rows of other digits, leaving other symbols intact

Review of the getchar and putchar: portion

Testing the "With getchar and putchar:" code would be easier if given a function declaration to see clearly what are inputs and outputs.  Example:

void UpdigitsFilter_IO(void) {
// or
int UpdigitsFilter_IO(void) {

Code uses '.' as a terminator, but that is not listed as a design criteria.  Was this to be '\0'?
Code uses char c, whereas getchar() returns an int.  This causes issues in 2 places, when EOF is encountered and char outside the 0 - SCHAR_MAX (typically 127).  Proper use of is...() functions require values in the 0 to UCHAR_MAX range or EOF.

// char c = 0;
int c = 0;

Exiting the loop on EOF should occur  (2x  places)

// while ((c = getchar()) != '.')
while ((c = getchar()) != '.' || c == EOF)

There is a discrepancy between "ascending digits" and if (c - c_ == 1).  The first implies "135" is acceptable as the digits are greater than previous, but code implies they need to be sequential.  Assume sequential.
The requirements are silent on single digits sequences.  Assume acceptable.
Check the return value of putchar().  Maybe make this the function's return when non-zero.

int retval = putchar(ch);
if (retval) {
  return retval;
}

Filtering will not stop if a '.' is encountered in the inner c = getchar();.  Add checks here for '.' and EOF.


params (version 1)
You can use the same trick the Rows.Add method uses namely the params keyword

By using the params keyword, you can specify a method parameter that takes a variable number of arguments.

and pass columns names as the last parameters. Then you read the values form the reader with some LINQ and turn it into an array because it's just that, an array (but one that is created dynamically if each value is passed separately). Besides you don't need two ifs, use the and && operator instead.
public void FillColumns(
    DataTable table,
    OracleDataReader  reader,
    params string[] columnNames)
{
    if (reader != null && reader.HasRows)
    {
        table.Rows.Clear();
        while (reader.Read())
        {
            table.Rows.Add(columnNames.Select(name => reader[name]).ToArray());
        }
    }
}

Example call:
.FillColumns(table, reader, "Column1", "Column2");

table.Columns (version 2)
the second approach would be to read the column names from the data table
public void FillColumns(DataTable table, OracleDataReader reader)
{
    if (reader != null && reader.HasRows)
    {
        table.Rows.Clear();
        while (reader.Read())
        {
            table.Rows.Add(
                table
                .Columns
                .Cast<DataColumn>()
                .Select(column => reader[column.ColumnName])
                .ToArray());
        }
    }
}

table.Load (version 3)
and the third to just load the datatable from the reader:
public void FillColumns(DataTable table, OracleDataReader reader)
{
    if (reader != null && reader.HasRows)
    {
        table.Rows.Clear();
        table.Load(reader);
    }
}


As you mentioned, the nested comprehension is not very intuitive. I had to write it out for understanding.

I am also not sure I understood your requirements correctly. Please correct any wrong assumptions. These are the attempts:

from itertools import chain

def join(vars_):
    filtered = (element for element in vars_ if element)
    return chain.from_iterable(filtered)

num = ((1, 2), None, [1, (2, 3)], None)
let = (('a', 'b'), ['a', ('b', 'c')], None, None)
vars_all = (let, num)

for i, vars_ in enumerate(zip(*vars_all), start=1):
    print(f"Case {i}:", join(vars_))

It returns

Case 1: <itertools.chain object at 0x00000221C73F3940>
Case 2: <itertools.chain object at 0x00000221C73F3940>
Case 3: <itertools.chain object at 0x00000221C73F3940>
Case 4: <itertools.chain object at 0x00000221C73F3940>

So not what you really asked for. However, the chain object behaves like a normal list in most circumstances. It supports the Sequence interface (but not the MutableSequence interface):

from collections.abc import MutableSequence, Sequence
from itertools import chain

def join(vars_):
    filtered = (element for element in vars_ if element)
    return chain.from_iterable(filtered)

num = ((1, 2), None, [1, (2, 3)], None)
let = (("a", "b"), ["a", ("b", "c")], None, None)
vars_all = (let, num)

for i, vars_ in enumerate(zip(*vars_all), start=1):
    print(f"Case {i}:", list(join(vars_)))
    print("\tIs Sequence:", isinstance(vars_, Sequence))
    print("\tIs MutableSequence:", isinstance(vars_, MutableSequence))
    print(
        "\tIs MutableSequence (cast to list):", isinstance(list(vars_), MutableSequence)
    )

will print

Case 1: ['a', 'b', 1, 2]
        Is Sequence: True
        Is MutableSequence: False
        Is MutableSequence (cast to list): True
Case 2: ['a', ('b', 'c')]
        Is Sequence: True
        Is MutableSequence: False
        Is MutableSequence (cast to list): True
Case 3: [1, (2, 3)]
        Is Sequence: True
        Is MutableSequence: False
        Is MutableSequence (cast to list): True
Case 4: []
        Is Sequence: True
        Is MutableSequence: False
        Is MutableSequence (cast to list): True

So if a caller requires a list, they can cast to that type specifically. It is perhaps more pythonic to not do that in the function already (duck-typing).

Another point to note is that if both elements are None, an empty iterable is returned. This will still behave similar to None in boolean contexts. It allows for simpler code and maybe more predictable returns. See if that still fulfills your requirements. If not, this final suggestion will fulfill your tests as specified:

from itertools import chain

def join(vars_):
    if not any(vars_):
        return None
    filtered = (element for element in vars_ if element)
    return list(chain.from_iterable(filtered))

num = ((1, 2), None, [1, (2, 3)], None)
let = (("a", "b"), ["a", ("b", "c")], None, None)
vars_all = (let, num)

for i, vars_ in enumerate(zip(*vars_all), start=1):
    print(f"Case {i}:", join(vars_))

will return

Case 1: ['a', 'b', 1, 2]
Case 2: ['a', ('b', 'c')]
Case 3: [1, (2, 3)]
Case 4: None

for Python 3.8.1.
I hope you agree that this is more readable, intuitive and also debuggable.
The early return makes it easier to understand. The additional itertools import is very cheap.

Finally, a one-liner version of the above is

def join(vars_):
    return list(chain.from_iterable(elem for elem in vars_ if elem)) or None

Lastly, two notes:

notice the start keyword for enumerate
leading underscores denote (private) implementation details; use trailing underscores for variable names that otherwise shadow built-ins; better to avoid these all-together, though


Number of iterations is pretty low. Since .NET's PBKDF2 implementation is very slow, you can't afford a good number of iterations. But even with it, 20000 should be affordable for server side hashing. For client side hashing you can go much higher.
You're outputting more than the natural size (20 bytes for SHA-1), which decreases performance twofold without a security gain. At the same cost you could double the number of iteration, which improves security.

=> Increasing the output size beyond 20 bytes decreases security for a given hashing cost.
SlowEquals is a bad name. I'd call it ConstantTimeEquals.
No point in having large salts. Salts should be globally unique. 16 bytes is enough for that, so going beyond that doesn't increase security.
There are no known weaknesses in SHA-1 (or even MD5!) that apply to password hashing. Collision attacks are no threat in this context. The most important distinction between different hashes is the relative software (CPU) vs. hardware (GPU, FPGA, ASIC) performance. So on a 64 bit CPU, SHA-512 is probably a decent choice since it relies on 64 bit arithmetic.


Watch your memory allocations and deallocations. In both cases, you've got defangIPaddr returning a const char * to heap-allocated memory, which needs to be freed by the caller... but it can't be freed, because free expects a non-const void* as its argument.
Functions that return ownership-of-a-heap-allocation to the caller should (A) return char*, not const char*, and (B) be clearly documented.
In Code 2, you're not just leaking the returned pointer; you're also leaking the strdup'ed original pointer. There's no reason to call strdup here.
What you want is simply
char *defangIPaddr(const char *address) {
    char *defanged = calloc(sizeof("###[.]###[.]###[.]###"), 1);
    char *q = defanged;
    for (const char *p = address; *p != '\0'; ++p) {
        if (*p == '.') {
            *q++ = '[';
            *q++ = '.';
            *q++ = ']';
        } else {
            *q++ = *p;
        }
    }
    return defanged;
}

I've shortened your names character and ipv4_memory to just p and q. My p is for "pointer"; it's not a character at all, so character is a misleading name for it. q is simply what comes after p.
You got the arguments to calloc in the wrong order. In practice this doesn't matter; but getting it correct is easy and free. If you're unsure about an interface, check the man page.
In your original code, you did this:
char* cloned_address = NULL;
cloned_address = strdup(address);

That's a verbose way of writing
char* cloned_address = strdup(address);

Always initialize your variables — but initialize them to the right values! Don't initialize to a nonsense or garbage value and then later assign the right value over it; just initialize with the right value to begin with.

sizeof("###[.]###[.]###[.]###") is a mildly sneaky way of computing the maximum possible length. It might be better to allocate simply 3*strlen(address)+1 bytes, so that you can't possibly buffer-overflow, even if the caller passes in ".................." as their input.
Alternatively, you could compute the exact right buffer length and malloc exactly that much.
    int len = 0;
    for (const char *p = address; *p != '\0'; ++p) {
        len += (*p == '.') ? 3 : 1;
    }
    char *defanged = calloc(len+1, 1);
    [...]

Consider throwing in an if (defanged == NULL) return NULL; just in case the allocation fails.


Is my equivalent of Excel's "EOMONTH" function correct?

For your implementation, why not use:

return ((new DateTime(dateTime.Year, dateTime.Month, 1)).AddMonths(1 + months).AddDays(-1));

To me, that's a little cleaner, but it might just be me. When I'm just creating an object to be returned, I'm not a fan of storing it in a variable. Instead, just return exactly what you mean to and be done with it.

For your test cases:

I'm not sure that it matters in this instance, since you are relying exclusively on built in methods, but I would create test cases around February and March for the various types of leap years. What if I specify February 29th on a non-leap year? Does it work for the different leap year conditions? I'd also create test cases around new years (December and January).


Opening files using fopen only if user enters correct password

Don't repeat yourself. This block of code appears twice. It would be better to extract it to a separate function and reuse it:

        if((fp=fopen("text","r")) != NULL)
        {
                while((c=getc(fp)) != EOF)
                {
                        putchar(c);
                }
                fclose(fp);                     //close the file once done
        }
        else
        {
                perror("Error:");
                return(-1);
        }

Btw, is there a reason to read and print the file contents character by character? It would be more efficient to do it buffer by buffer.

Also, the comment is pointless, that line is self-explanatory.

In this code:

if(strcmp(password,input)==0)
{
        // ...
}
else if(strcmp(password,input) != 0)

The else if condition can be replaced with a simple else. That's less typing, and again, don't repeat yourself!


ResettableLazy: a resettable version of .NET Lazy

Overall, it looks good to me.  There aren't any real threading concerns with simultaneously resetting and accessing the value.  The body of the Value property getter will either use the old _lazy or the new _lazy, but those are the only options.  Since there isn't any locking it is possible for one thread to continue to see the old value after another thread resets (due to caching a value of the _lazy reference), but this is likely not a problem in most use cases.

One thing to note is that if Lazy<T>.IsValueCreated ever becomes true it stays true for the lifetime of the object, and this is not the case with your class.  It's worth calling out that if the object is shared between threads than many of the reasons to use IsValueCreated become less reliable (e.g. accessing .Value may be expensive).


Code

Prefer std::array over plain C-style arrays. It has more normal copy / assignment semantics (which admittedly isn't relevant here), but also allows you to access the size directly from the array.
Naming:

head is usually used for the first populated element (of a list, for example). In this case it refers to the first empty space instead, so next might be a more appropriate name.
avg, itr: prefer full names over abbreviations.
_mutex: the underscore prefix is usually used to denote a member, but this is the only member that has one?
sum would be a better name than tmp. It's also better to declare variables as close as possible to the point of use.

double sum = 0.;
for (auto i : data) // range-based for loop for brevity
    sum += i;

Sum loops like this may also be written using the std::accumulate algorithm:

    #include <numeric>
    ...
    using std::begin;
    using std::end;
    auto sum = std::accumulate(begin(data), end(data), 0.0);

When referring to _mutex in member functions, the code uses this->_mutex. Which rather defeats the point of using the underscore prefix. No other members are referred to with this->.
The itr and head variables are unnecessary, as they can both be trivially calculated: itr = counter / N; head = counter % N;
Getter functions, e.g.count(), average() should be const. Note that for this to compile, the mutex member must then be made mutable (one of the few instances where mutable is to be recommended).

Design

This appears to be a Cumulative Moving Average. Data storage is actually unnecessary for such an average! (Which can be seen in the existing code since  the data is periodically overwritten. There is no advantage in creating an Average<double, 1297> over an Average<double, 1>. The average() function will return the same result for the same data regardless.)

Since the data is private and cannot be accessed externally, it becomes irrelevant... As such, most of the code can be deleted! :)

class CumulativeMovingAverage
{
    std::size_t n;
    double average;

public:

    CumulativeMovingAverage(): n(0u), average(0.0) { }

    std::size_t get_count() const
    {
        return n;
    }

    double get_average() const
    {
        return average;
    }

    void update(double x)
    {
        // formula straight from wikipedia:
        //average = (x + n * average) / (n + 1u);
        //++n;

        // improved formula from Toby Speight (see comments):
        ++n;
        average += (x - average) / n;
    }
};

Thread safety / templateyness is left as an exercise to the reader (the original code looks correct to me).


One possible improvement is to use recursion and memoization to implement a "dynamic programming" solution. This uses the results of previous calculations to speed up the process, as you will end up calculating the same sub-sequences repeatedly. For example:

def memo(f):
    def func(*args):
        if args not in func.cache:
            func.cache[args] = f(*args)
        return func.cache[args]
    func.cache = {}
    return func

@memo
def collatz(n):
    if n == 1:
        count, seq = 0, []
    elif n % 2:
        count, seq = collatz(3 * n + 1)
    else:
        count, seq = collatz(n // 2)
    return count + 1, [n] + seq

(Note the use of a decorator to implement the memoization.)

Now, once you've run:

>>> collatz(10)
7, [10, 5, 16, 8, 4, 2, 1]

then e.g. collatz(8) can just be looked up from the cache, so future calculations aren't needed:

>>> collatz.cache
{(1,): (1, [1]), (2,): (2, [2, 1]), (8,): (4, [8, 4, 2, 1]),
 (4,): (3, [4, 2, 1]), (10,): (7, [10, 5, 16, 8, 4, 2, 1]),
 (5,): (6, [5, 16, 8, 4, 2, 1]), (16,): (5, [16, 8, 4, 2, 1])}

The downsides of this are:

It uses up a lot of space; and
As it's recursive, a long sequence can hit the recursion limit and crash the program.

Also, note that count == len(seq), so you don't necessarily have to return (and store) both.


Your use of the temp variable makes your code particularly infuriating to follow:

It's not even that temporary in scope: it's used throughout the function!
temp is almost never a good name for a variable, since it doesn't give any clue what it is supposed to represent.
You redefine and repurpose it several times within the function.
There are too many if(num%2==0) special cases.  You shouldn't need any special cases if you just use the truncation that naturally happens with integer division in your favour.

For that matter, num is also a meaningless variable name.  I can see that it's an int, which is, obviously, a number.  How about size instead?

There's a lot of copy-and-paste code.  You could benefit greatly splitting the work into functions.  Decomposing the task would also force you to think about what the subroutines are, and help you organize your code.

Calling System.out.print() to print each character at a time is very tedious.  It's also bad for performance, if that matters to you.  A much better strategy would be to create a buffer to print at least a line at a time, if not the entire picture at once.  Another benefit of using a buffer is that you can just place the stars in the right place using a formula.

Suggested solution

import java.util.Arrays;

public class Phi {
    /**
     * Produces a string of spaces that has the character c
     * at the three specified indices, followed by a newline.
     */
    private static String row(char c, int left, int mid, int right) {
        char[] line = new char[right + 2];
        Arrays.fill(line, ' ');
        line[left] = line[mid] = line[right] = c;
        line[right + 1] = '\n';
        return new String(line);
    }

    public static String toString(char c, int size) {
        StringBuilder out = new StringBuilder();
        int halfWidth = (size + 1) / 2;

        // Top stem
        out.append(row(c, halfWidth, halfWidth, halfWidth));

        // Body
        for (int row = 2; row <= size / 2; row++) {
            out.append(row(c, halfWidth - row, halfWidth, halfWidth + row));
        }
        for (int row = halfWidth; row >= 2; row--) {
            out.append(row(c, halfWidth - row, halfWidth, halfWidth + row));
        }

        // Bottom stem
        out.append(row(c, halfWidth, halfWidth, halfWidth));

        return out.toString();
    }

    public static void main(String[] args) {
        int size = Integer.parseInt(args[0]);
        System.out.printf("\nNumber = %d\n%s", size, toString('*', size));
    }
}


Logfile parser for Team Fortress Classic video game

Your 3rd question is off-topic for the site, but I do believe that you are using the one-to-many relationships correctly.

When you are finding a player by steam_id you don't actually need to select the steam_id unless you are going to use it for something in an application.  This will speed up the query (probably not enough to be visible though).

Another thing, and this is just a thought because I am not positive on how this works:

In your players table you could change the primary key to be the Steam ID since that is always going to be unique and you are always going to give that as a value on the insertion of a record.

On the same note, you can change the foreign key of the aliases table to be the Steam ID as well.

Still add the Constraint of NOT NULL, Primary Key And Foreign Key as appropriate.


Why are you getting day in function getWeekday and never using it?
Use a IIF (Immediately Invoked Function) to close over constants so they do not need to be created each time you call the function that uses them (Note optimizer will cache such constants, though not on the first pass)
Don't add unneeded details to names. booking is unrelated to the functions role, and should not be part of the name.
You have added complexity where not needed.

The functions getWeekday and monthName are just array look ups and can be done directly via the index you pass the functions.
Almost all the variables you use are once off uses, you can side step the source and execution overhead by referencing the data directly.

Be consistent in naming getWeekday and monthName do about the same thing yet the names are completely different. dayName and monthName would be more consistent.
Use constants for variables that do not change.

Example 1

Use an IIF to define constants and returns a function that formats the date.
Added date as an argument that defaults to new Date

Rather than creating an array by hand I use a short cut to convert a delimited string to an array. I find this easier to create string arrays this way.

const formatDate = (() => {
    const DAYS = "Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".split(",");
    const MONTHS = "January,February,March,April,May,June,July,August,September,October,November,December".split(",");
    return (date = new Date()) => ` ${DAYS[date.getDay()]}, ${MONTHS[date.getMonth()]}  ${date.getDate()},  ${date.getFullYear()}`;
})();

Example 2

Keeping to your original logic and layout, but behind an IIF. Note all the constants.

const formatNow = (() => {
    const DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    const dayName = idx => DAYS[idx];
    const monthName = idx => MONTHS[idx];
    function format() {
        const now = new Date();
        const day = now.getDay();
        const date = now.getDate();
        const month = now.getMonth();
        const year = now.getFullYear();
        return ` ${dayName(day)}, ${monthName(month)}  ${date},  ${year}`;
    }
    return format;
})();


Efficient Implementation of functional and Lazy evaluation in C++

I think this question may be off-topic, as it does not consist of complete working code to be reviewed. I spent (too long) trying to get it to compile, and got as far as this: https://godbolt.org/z/qCE9S8

But you have a lot of problems with the current design. Most notably, you're using raw new all over the place, which creates pointers to the heap; but you aren't actually using the correct syntax to refer to those pointers. For example:

Stream<N> map(function<N(T)> mapper) {
    return new MapStream<N,T>(this, mapper);
}

Here new MapStream<...>() yields a value of type MapStream<N,T>*, but you're trying to return it as if it were a Stream<N> object. This flatly will not compile.

You could consider changing this return type to std::unique_ptr<Stream<N>> (and using make_unique), but that still won't really work for your use-case, because then you'll have to change this line:

stream.map(hash1).map(hash2).foreach(summer);

to:

stream.map(hash1)->map(hash2)->foreach(summer);

because now map returns a pointer. And worse, there's no way for the MapStream object itself to transfer its own ownership into the previous_ member of the next MapStream object in the chain. You end up with a bunch of temporary unique_ptrs, all linked together by raw pointers which will dangle as soon as the current full-expression finishes. That's okay for your benchmark, but it won't work at all in practice.

You might consider looking at a type erasure design, so that you could keep using Stream<int> as a value type (not a polymorphic base class, no visible pointers) but give it behavior that appeared polymorphic at run time.


Minimum steps to 1 to find minimum operations to transform n to 1

Your function is right.

However, for dynamic programming I always propagate state n to all states n+1 (Forward). Your code calculates state n+1 from state n (Backward). In this case both methods are okay and it is mostly a personal preference. But in other cases the backward method may run into problems that state n is not yet calculated.

function minStepstoOne2(n) {
  var steps = Array(n+1).fill(n);
  steps[1] = 0;

  for(let i = 1; i < n; i ++) {
    steps[i + 1] = Math.min(steps[i + 1], steps[i] + 1);
    if (i * 2 <= n)
      steps[i * 2] = Math.min(steps[i * 2], steps[i] + 1);
    if (i * 3 <= n)
      steps[i * 3] = Math.min(steps[i * 3], steps[i] + 1);
  }
  return steps[n];
}


Best practice for URL's architectural Design in Django

I've read the comments and am a bit torn by the discussion... yes, this code is not runnable; yes, you assume background knowledge; but you do that because 90% of Django starter code is not relevant to this discussion, but is essential to a Django project, so I think this is worth a shot.
For starters, it's worth pointing out that which of these solutions you choose has no impact on the code you write, since you will always refer to URL's by their name rather than by their path. This is solely a matter of beauty for how your capabilities are exposed to users and external services.
For this case, I would suggest a refactor that separates the front-end (paths) from the back-end (functionality). Have an app each for support, blog, and store, each of which implement their own models, serializers, utility functions, Celery tasks, etc. Then, have an app each for panel and administration that implements the paths, views, and user-facing logic about how people interact with those underlying concepts. You end up with some internal dependencies, but they're bipartite (only apps in the "frontend" group depend on only apps in the "backend" groups) and acyclic, so that's not a big deal.
If designed this way, you get the best of both worlds. You can keep the logical separation you show above among isolated logical components, but can use clean path construction and view implementation designed around how the users interact with your system. The downside is a larger number of apps and some internal dependencies, but those dependencies become explicit and you avoid the apps needing to implicitly know about each other and knowing how to avoid path conflicts.


Operator overloading for Boost interval (vectors)

I'll start by saying I haven't used boost::numeric, so what I say here is based on a quick skim of its documentation and source.

Instead of writing the constant 3 in so much of the code, we should be using rows() or cols() as appropriate (or perhaps even RowsAtCompileTime and ColsAtCompileTime).

Don't pass simple value types by reference - double values should be simply passed by value.

In fact, since Eigen::Matrix has a member that multiplies by a scalar, we can simplify these functions by simply calling that.  All we have to do is swap the argument order:

Vector operator*(double x, Vector y)
{
    return y *= x;
}

Matrix operator*(double x, const Matrix& y)
{
    return y * x;
}

We can also simplify the dot-product function by using the standard inner_product algorithm.  We need to know that a vector's start and end iterators are obtained by data() and data() + size() respectively:

#include <numeric>

Interval inner_prod(const Vector& x, const Vector& y)
{
    return std::inner_product(x.data(), x.data() + x.size(),
                              y.data(), Interval{});
}

Interval inner_prod(const std::vector<double>& x, const Vector& y)
{
    if (x.size() != y.size())
        return {};              // or throw an exception, or something
    return std::inner_product(x.begin(), x.end(),
                              y.data(), Interval{});
}


Iterative Implementation of Towers of Hanoi

Wow. Some legible matlab code. I'm impressed. Too often matlab seems to be a "write only" language, in the sense that perl regex line noise or Iverson's APL can be write only.

No biggie, but I wouldn't mind seeing consistent comment formatting where (N, from, to, alt) appear in the left margin in each of four separate lines. Kudos for telling us about the args, anyway. In the matlab ecosystem this is maybe redundant, but speaking for myself I wouldn't mind seeing a reminder that there's no zero-origin going on here, by mentioning from > 0 or something. Saying it once would suffice - to & alt would clearly use the same convention. I see that later you spell this out in the "avoid index = 0" comment.

typo: Returs

Kudos on helpfully explaining that 2^N-1 is totalNumberOfMoves.

Your figure was helpful. The "from -> alt -> to" comment is on the redundant side.

Would you do the Gentle Reader a small favor, please, and bump the currentPositions and len assignments down slightly? Just a few lines. That way we have a full-line comment on the "odd" case, setting up dramatic tension for "what about even?", and the swapArrays immediately shows the even case.

Switching from j to k for the path2 case was maybe a little odd. Wouldn't hurt to stick with j, as we always assign it a value at top of loop. Switching to k made me wonder if variable value needs to survive until some subsequent iteration.

Renaming deal to swapArrays made sense, thank you.

Comment for generateDiskMoves is very nice. Except I'd delete that "m is discarded" remark, as that's not part of the public API.

Personally I view the comment for M .+ 1 as "% Convert to one-origin moves."

The "Get only the first move" comment is accurate and helpful, but consider something stronger: "% The trivial case requires just one move."

Omega2 accepts lowercase n. Consider using lowercase in the other functions. I had been thinking of upper as matrix and lower as scalar.

I wouldn't mind seeing a comment that spells out whether disk 1 is smallest or biggest disk.

As far as the algorithm goes, if results of a parity function were available, could you verify, or synthesize, the Omega2 results? Perhaps with less looping?


Simple C++ program to check win in TicTacToe

Computing a square-root is unnecessary; further, it only works when kBoardSize is a perfect square. Prefer

const int kBoardLength = 3;
const int kBoardSize = kBoardLength * kBoardLength;

Your test for unreachability is not complete. You verify that O has made no more moves than X, but you really need to check that the winner made the last move. If X won, then should have numberOfX = numberOfO + 1; if O won then should have numberOfO = numberOfX. It should be clear how to add these checks to your CheckTicTacToeBoard method.
A more overarching tension in this code is: should the board size really be a constant? The code is written so abstractly as to support any board size. But then the board size is fixed to a constant. I would choose one of the following directions to proceed in:

Commit to a board size of 9. In this case, I would recommend hard-coding the win conditions in winDetection. There are only 8 ways to win, so the resulting code would be a lot cleaner.
Allow arbitrary board sizes. In this case, you should accept a boardLength argument. Further, you will have to refine the notion of an UnreachableState. For example, in 5-by-5 tic tac toe, the following state is unreachable, your code would return Xwins:

x x x x x
o . o . o
x x x x x
o . o . o
o o x o o


Calculating a table of deBroglie wavelengths for various electron energies

First, simplify: factor out \$C^4\$ out of square root:

\$\lambda(E_k) = h\left/C\sqrt{(\frac{E_k}{C^2}+m_e)^2-m_e^2}\right.\$

Simplify even more: factor out \$m_e^2\$:

\$\lambda(E_k) = h\left/C m_e\sqrt{(\frac{E_k}{(C m_e)^2}+1)^2-1}\right.\$

Do not put everything in lambda:

# These are all constants; no need to recompute them.
# Consider putting them into a namespace.
# I didn't think too hard to figure appropriate names; my physics is too rusty

CM = spc.c * spc.me
e1 = spc.ev/(CM * CM)
scale = spc.h / CM

# This is an actual computation.
# Can be converted to lambda, but I strongly advise against.

def deBroglieWaveLength(n):
    arg = e1 * n + 1.0
    return scale / np.sqrt(arg * arg - 1)


Google CodeJam 2016 - Python Counting Sheep

In general, it is difficult to follow the logic and the code is not readable.

First, here are some general things you can improve:

N.rstrip() does not modify a string in place and returns a new string instead. Since you are not assigning the result to anything, it does nothing
according to PEP8, you should put underscores between the words in variable and function names - number_of_tries vs numberoftries or digitlist vs digit_list, get_number() vs getnumber()
following the previous note - N is not a good variable name
remove unused import
count = count + 1 can be rewritten as count += 1
put the main logic of the program into if __name__ == '__main__':
use print() function instead of a statement for Python 3.x compatibility
use with context manager when opening file(s) - this will ensure it being properly and safely closed
use os.path.join() to join the path components (okay, you now need to get your import os back :)
define constants in upper case (PEP8 reference)
use list comprehensions
use .format() instead of string concatenation
use built-in sum() function to for counting
loop over the items directly instead of indexes

The code after applying the changes:

import os

NUMBER_OF_TRIES = 1000
BASE_DIRECTORY = '/home/username/GoogleCodeJam/'
INPUT_FILE_NAME = 'A-large-practice.in'
OUTPUT_FILE_NAME = 'largeoutput'

def get_number(number, number_of_tries):
    print("new case number = {number}".format(number=number))

    digit_list = []
    current_number = number
    for j in range(1, number_of_tries):
        number_as_string = str(current_number)

        digits = []
        for item in number_as_string:
            if item not in digits:
                digits.append(item)

        for digit in digits:
            if digit not in digit_list:
                digit_list.append(digit)

        count = sum(1 for k in range(0, 10) if str(k) in digit_list)
        if count == 10:
            print("count = 10")
            return number_as_string
        else:
            current_number = number * (j + 1)
            print("number = {number}".format(number=number))

    return "INSOMNIA"

if __name__ == '__main__':
    input_file_name = os.path.join(BASE_DIRECTORY, INPUT_FILE_NAME)
    output_file_name = os.path.join(BASE_DIRECTORY, OUTPUT_FILE_NAME)

    with open(input_file_name, "r") as input_file, open(output_file_name, "w") as output_file:
        number_of_cases = next(input_file)
        for case_number in range(1, int(number_of_cases) + 1):
            number = int(next(input_file))
            result = get_number(number, NUMBER_OF_TRIES)

            output_file.write('Case #{case_number}: {result}\n'.format(case_number=case_number, result=result))

Alternative Solution:

We can also improve on both the performance and readability if we would use sets - collecting the digits seen so far until the length of the set is 10 (collected all digits) or we reach the maximum number of tries:

def get_number(number, number_of_tries):
    digits = set([])  # keep track of all seen digits

    current_number = number
    for j in range(1, number_of_tries):
        digits |= set(str(current_number))  # add new digits to the seen set

        if len(digits) == 10:  # exit if collected all the digits
            return current_number
        else:
            current_number = number * (j + 1)

    return "INSOMNIA"


Counting the occurrences of a string in each file

The first comment is that your code doesn't handle exceptions at all. You open a FileInputStream but you do not close it in case of exceptions. This can lead to a resource leak. Beginning with Java 7, you can use the try-with-resources statement to make sure that all open streams are closed properly. Instead of having

FileInputStream fstream = new FileInputStream(file);
BufferedReader in = new BufferedReader(new InputStreamReader(fstream));

you would have

try (FileInputStream fstream = new FileInputStream(file);
     BufferedReader in = new BufferedReader(new InputStreamReader(fstream));
) {
    // do the rest here
}

When the try block will finish, whether normally or exceptionally, all the streams that were opened in the try initialization block will be closed.
You don't need to wrap your stream into a InputStreamReader and a FileInputStream. You can just use a FileReader that does this already, turning your code into

try (BufferedReader in = new BufferedReader(new FileReader(file))) {
    // do the rest here
}

When the BufferedReader will be closed, it will also close the underlying FileReader.
You should prefer to program against interfaces and not implementation. Consider changing this

HashMap<String, Integer> result = new HashMap<String, Integer>();

to this

Map<String, Integer> result = new HashMap<String, Integer>();

or even

Map<String, Integer> result = new HashMap<>();

since you don't need to reiterate the type parameters since Java 7. In the same way, your method could return a Map<String, Integer> instead of a HashMap<String, Integer>.
Try to remove commented out code like // System.out.println(fileName);.


I do not like the functional approach of this, especially since you are "inheriting" the user_input by number_input.
Here's an object-oriented version:

#! /usr/bin/env python3

class UserInput:

    def __init__(self, prompt=None, *, errors=None, values=None, process=None,
                 wanted=None, default=None, end=None):
        self.prompt = prompt
        self.errors = errors
        self.values = values
        self.process = process
        self.wanted = wanted
        self.default = default
        self.end = end

    def __call__(self):
        return self.get()

    @property
    def prompt(self):
        """Returns the prompt."""
        prompt = self._prompt or ''

        if self.values:
            prompt += '[{}] '.format('/'.join(str(i) for i in self.values))

        if self.end is not None:
            prompt += self.end
        elif self.values:
            prompt += '\n> '

        return prompt

    @prompt.setter
    def prompt(self, prompt):
        self._prompt = prompt

    @property
    def errors(self):
        return self._errors or tuple()

    @errors.setter
    def errors(self, errors):
        self._errors = errors

    @property
    def values(self):
        return self._values

    @values.setter
    def values(self, values):
        self._values = set(values) if values is not None else None

    @property
    def process(self):
        return self._process or (lambda v: v)

    @process.setter
    def process(self, process):
        self._process = process

    @property
    def wanted(self):
        """Returns the wanted callback."""
        if self._wanted:
            return self._wanted
        elif self.values is None:
            return lambda _: True

        return lambda value: value in self.values

    @wanted.setter
    def wanted(self, wanted):
        self._wanted = wanted

    def get(self):
        """Retrieves the user input."""
        while True:
            try:
                value = input(self.prompt)
            except (EOFError, KeyboardInterrupt):
                if self.default is not None:
                    return self.default

                raise

            try:
                value = self.process(value)
            except self.errors:
                continue

            if self.wanted(value):
                return value

class NumberInput(UserInput):

    def __init__(self, prompt=None, *, errors=ValueError, values=None,
                 process=int, wanted=None, end=None):
        super().__init__(
            prompt, errors=errors, values=values, process=process,
            wanted=wanted, end=end)

def main():

    name_input = UserInput('What is your name? ')
    age_input = NumberInput('What is your age? ')
    day_input = NumberInput('Day: ', values=[1, 2, 3, 4, 5])
    again_input = UserInput('Again? ', values='yn', process=lambda v:v.lower())

    print('Hello, {}! You are {}.'.format(name_input(), age_input()))
    print('You want day {}'.format(day_input()))
    print('You {}want to go again.'.format('' if again_input() == 'y' else "don't "))

if __name__ == '__main__':
    main()

I also added an additional keyword argument default the value of which will be returned on KeyboardInterrupts and EOFErrors (which occur on pressing [Ctrl]+[D]) iff specified.

Regarding the function of the code itself, I think that it is trying to be a jack-of-all-trades-device and doing a bad job at it while violating the YAGNI principle.
User input is highly variable and dynamic. If you think of a simple yes/no question where yes should be default (if one just hits enter) and the prompt should highlight the default value like in the pacman prompt below, this is really hard to implement using your functions (or classes).

$ LANG=en_US sudo pacman -S kate
resolving dependencies...
:: There are 2 providers available for phonon-qt5-backend:
:: Repository extra
   1) phonon-qt5-gstreamer  2) phonon-qt5-vlc

Enter a number (default=1):   # Just hit [Return] here.
looking for conflicting packages...
warning: dependency cycle detected:
warning: phonon-qt5-gstreamer will be installed before its phonon-qt5 dependency

Packages (43) attica-qt5-5.38.0-1  editorconfig-core-c-0.12.1-2  kactivities-5.38.0-1  karchive-5.38.0-1  kauth-5.38.0-1  kbookmarks-5.38.0-1  kcodecs-5.38.0-1  kcompletion-5.38.0-1  kconfig-5.38.0-1
              kconfigwidgets-5.38.0-1  kcoreaddons-5.38.0-1  kcrash-5.38.0-1  kdbusaddons-5.38.0-1  kglobalaccel-5.38.1-1  kguiaddons-5.38.0-1  ki18n-5.38.0-1  kiconthemes-5.38.0-1  kio-5.38.0-1
              kitemmodels-5.38.0-1  kitemviews-5.38.0-1  kjobwidgets-5.38.0-1  knewstuff-5.38.0-1  knotifications-5.38.0-1  kparts-5.38.0-1  kservice-5.38.0-1  ktexteditor-5.38.0-1  ktextwidgets-5.38.0-1
              kwallet-5.38.0-1  kwidgetsaddons-5.38.0-1  kwindowsystem-5.38.0-1  kxmlgui-5.38.0-1  libdbusmenu-qt5-0.9.3+16.04.20160218-1  media-player-info-22-2  phonon-qt5-4.9.1-4
              phonon-qt5-gstreamer-4.9.0-3  polkit-qt5-0.112.0+git20160226-1  qt5-multimedia-5.9.1-2  qt5-speech-5.9.1-2  solid-5.38.0-1  sonnet-5.38.0-1  syntax-highlighting-5.38.0-1  threadweaver-5.38.0-1
              kate-17.08.1-1

Total Download Size:    37.95 MiB
Total Installed Size:  146.67 MiB

:: Proceed with installation? [Y/n]  # Default option is capitalized.


Some comments:

if($_SERVER["HTTPS"] != "on")

See: https://stackoverflow.com/a/2886224/59087

Avoid calling exit() from more than one location.

The following code is repeated many times:

//this guy did not pass by login!
header("location:Login.php");
exit();

You could write some functions to avoid the duplication:

function redirectLogin() {
  redirect( "Login.php" );
}

function redirect( $page ) {
  header( "Location: $page" );
  exit();
}

This removes the duplication and ensures that you have only one place in the code to change if you wanted to rename Login.php, for example, to login.php, which is a bit more user-friendly (on Unix systems).


Combining ADD and VOLUME on a nodejs Dockerfile

This Dockerfile should contain:

FROM node:6.11-alpine

COPY . /code
WORKDIR /code

RUN npm install -g -s --no-progress yarn && \
    yarn && \
    yarn run test && \
    yarn cache clean

EXPOSE 8080

CMD ["npm", "start"]

COPY copies your current directory to /code for building the final image (that holds compiled code normally).

In your docker-compose.yml, mounting a volume is used for your dev purposes, so that the files modified replace the ones on your image.

version: "3"

services:
  web:
    build: .
    volumes:
      - .:/code
    command: "npm run start:dev"
    ports:
      - "8080:8080"
    networks:
      - internal

networks:
  internal:


Four-lines script to make an immediate DB and document root zip backup

Bug?

It looks to me that the name of the zip file used in the first and the last command were intended to be the same, that is the ${drt}/db-$(date +\%F-\%T).zip part:

mysqldump ... | zip ${drt}/db-$(date +\%F-\%T).zip
...
rm -rf  ${drt}/db-$(date +\%F-\%T).zip

They will only be the same if the mysqldump and rm commands run within the same second.

Don't repeat yourself

If a non-trivial command is expected to return the same value every time you run it, then extract it to a variable.
Not only to save unnecessary processing power,
but also to keep the non-trivial logic in one place,
so that it's easy to change if ever needed, in one place.

Double-quote command arguments

It's a good rule of thumb to double-quote command arguments when they contain variables,
to protect yourself from unintended word splitting and glob expansions.

Useless flags

In rm -rf  ${drt}/db-$(date +\%F-\%T).zip,
since we're deleting a file, not a directory,
the -r flag is useless.
Avoid useless flags.

Alternative solution

I suggest to write like this:

#!/bin/bash

date=$(date +\%F-\%T)

mysqldump -u root -p --all-databases | zip "${drt}/db-$date.zip"
zip -r "all_zipped-$date.zip" "${drt}"/ -x "*/cache/*"
rm -f "${drt}/db-$date.zip"


Rod-Cutting Problem using dynamic programming

I rather like your memo parameter.  It makes for a faster function.  If you are interested, Python 3.2 added the functools.lru_cache function that is used as a decorator and accomplishes the same thing as your memo.

Since possible_revenues is used just to find its max value, it would be more efficient to use a generator expression because the values are generated on demand instead of all being stored in memory.  To do that, simply change [ and ] to ( and ). edit: you would also need to change from ... + ... to itertools.chain(..., ...), importing itertools of course.  When you have an open bracket (any kind, {[(), the logical line continues until it is closed.  Because of that, you don't need the backslash at the end of the line.  I would also suggest that you put the open parenthesis for the second call to find_optimum_revenue() on the same line as the function name.  When I first saw those lines, it looked like you had used a variable and a tuple, but forgot to put a comma between them.

lambda functions are meant to be used where it would be awkward to define a function.  For example, you could use a lambda as an argument to sorted().  It is helpful because you don't need to go through the whole def line just for a one-time-use function.  If you are giving a name to a lambda function, that is a sign that it is not just a simple pass-it-to-another-function deal.  Naming lambdas is actually against PEP 8, the Python style guide.  Instead, use a def line.  If not for the reasons above, using def makes it easier to search for it.  If I want to search for a function  definition, I search for "def function_name(".  It would be hard to remember which functions were defined formally, and which were lambdas.


First things first, you should know about the order of evaluation in modifying forms:

  (operator preceding-form* place following-form*)

  The evaluation of each such form proceeds like this:

  Evaluate each of the preceding-forms, in left-to-right order.
  Evaluate the subforms of the place, in the order specified by the second value of the setf expansion for that place.
  Evaluate each of the following-forms, in left-to-right order.
  Read the old value from place.
  Compute the new value.
  Store the new value into place.

I'll take your idea with these changes:

Instead of !, I'll call it updatef
Instead of @, I'll use an identifying form, (:place <place>), where <place> is the actual place
Instead of splashing the form (e.g. (updatef delete 2 (:place *x*))), I'll make it a single destructuring argument of the macro (e.g. (updatef (delete 2 (:place *x*))))

I'm aware that this syntax is more verbose, but due to the specific nature of updatef's behavior, I think it shouldn't be used just about anywhere.

(defmacro updatef ((&whole form function &rest args) &environment env)
  (flet ((is-place-form (arg)
           (and (consp arg)
                (eq (card arg) :place)
                (consp (cdr arg)))))
    (let ((place-rest (member-if #'is-place-form args)))
      (assert (not (null place-rest)) ()
              "No place form in updatef.")
      (assert (null (member-if #'is-place-form (rest place-rest))) ()
              "More than one place form in updatef.")
      (let* ((preceding-forms (ldiff args place-rest))
             (place (second (first place-rest)))
             (following-forms (rest place-rest))
             (preceding-vars (loop for preceding-form in preceding-forms collect (gensym "preceding-var")))
             (following-vars (loop for following-form in following-forms collect (gensym "following-var"))))
        (multiple-value-bind (vars vals store-vars writer-form reader-form)
            (get-setf-expansion place env)
          (assert (= (length vars) (length vals)) ()
                  "Place expansion has different amount of variables than initializing forms in updatef.")
          `(let* (,@(mapcar #'(lambda (var form)
                                `(,var ,form))
                            (append preceding-vars vars following-vars)
                            (append preceding-forms vals following-forms)))
             (multiple-value-bind (,@store-vars)
                 (,function ,@preceding-vars ,reader-form ,@following-vars)
               ,writer-form)))))))

One of the good things that this macro does is to evaluate the subforms only once.  However, it doesn't help with certain kinds of places where it would be useful to operate atomically, such as setf of gethash or implementation specific atomic operations on places.

Here's a more permissive version that allows certain errors from setf expansions, namely: more or less vars than vals and a writer-form that doesn't return the new value(s).

Also, I made it so it does nothing special (regarding setf behavior) in case no form is (:place <place>), and to use the first such form in case there are more than one.

(defmacro updatef ((&whole form function &rest args) &environment env)
  (flet ((is-place-form (arg)
           (and (consp arg)
                (eq (card arg) :place)
                (consp (cdr arg)))))
    (let ((place-rest (member-if #'is-place-form args)))
      (cond ((null place-rest)
             (warn "No place form in updatef, no update generated.")
             form)
            (t
             (when (not (null (member-if #'is-place-form (rest place-rest))))
               (warn "More than one place form in updatef, first place will be used."))
             (let* ((preceding-forms (ldiff args place-rest))
                    (place (second (first place-rest)))
                    (following-forms (rest place-rest))
                    (preceding-vars (loop for preceding-form in preceding-forms collect (gensym "preceding-var")))
                    (following-vars (loop for following-form in following-forms collect (gensym "following-var"))))
               (multiple-value-bind (vars vals store-vars writer-form reader-form)
                   (get-setf-expansion place env)
                 (when (not (= (length vars) (length vals)))
                   (warn "Place expansion has different amount of variables than initializing forms in updatef."))
                 `(let* (,@(mapcar #'(lambda (var form)
                                       `(,var ,form))
                                   preceding-vars preceding-forms)
                         ,@(mapcar #'(lambda (var form)
                                       `(,var ,form))
                                   vars vals)
                         ;; In case there are more vars than vals
                         ,@(nthcdr (length vals) vars))
                    ;; In case there are more vals than vars
                    ,@(nthcdr (length vars) vals)
                    (let* (,@(mapcar #'(lambda (var form)
                                         `(,var ,form))
                                     following-vars following-forms))
                      (multiple-value-bind (,@store-vars)
                          (,function ,@preceding-vars ,reader-form ,@following-vars)
                        ,writer-form
                        ;; In case writer-form doesn't return the new value(s)
                        (values ,@store-vars)))))))))))

I'm sure that if you try, you can find many more places where to check for errors and warnings, and decide if you're permissive about them or not.  It has been quite a while since I've played with places myself.


Manager for image and JSON assets of a game

Naming and Commenting
An important part of being a programmer is good naming.
Looking at your code at first glance it seemed fine, until I started to rewrite it (I always rewrite when reviewing). For good code I should be able to rewrite the code without the need to go back to the original source for clarification. In this example I was constantly going back to try and understand what you were doing.
The main reason was that the name of variables that did not match what the variables contained and conflicted with important global names.
Comments
To make it worse the comments confused things even further
So let's examine the comments

/**
* Download an image and store it in the cache
* @param {string} url - Address of the image
* @param {string} name - Name of the image
* @param {function} onImageLoaded -Execute this function when all images are loaded

Last line is completely wrong, maybe?
  /* @param {function} onImageLoaded - callback for image onload event

3rd line not helpful , maybe?
 /* @param {string} name - Name used to store image in images object

2nd line, address? its a url or more apt a relative path to the image resource
1st line store it in a cache? Can't find any cache, but looking at the code I found the images object which you could call a cache, and download no you are not downloading in the classical sense of the word.
Maybe the following more clearly describes what the function does.
  /* Creates and loads Image adding it as a named object to images

The the second function's comments are as clear as mud

/* Download all images
 * @param {object} images -
 * @param {function} onImagesLoaded -

maybe
 /* Create and load images from an array image descriptions
  * @param {object} images - array of image descriptions contains url and name
  * @param {function} onImagesLoaded - Callback function called when all
  *                                    images in array have loaded.

I have to admit that the very first thing I do when reviewing code is remove all comments (they rarely help), so your comments did not confuse me, only when writing this did I read them.
If you are going to add comments they must make sense, for if they dont they only create confusion, and that will result in problems when you return in months to touch up the code.
Write comments addressed to a 3rd person that is not in your head space. Sure the images object is a cache, you know that but that is not obvious to anyone else.
Names
Names are short.
When you name a variable it is at the point where you define its scope, that scope gives the variable a context. You name a variable in its context and don't add redundant information that is clearly implied from the context.
For example you have the argument onImageLoaded for the function loadImage I would say that the 'Image' part of the name is rather obvious so why add it. onLoaded is shorter, does not create ambiguity.
Names create entities
When you name an object you create an entity in the mind of the person reading your code (that person will be you months from now). When you see that name you associate the entity. Associating a global name with multiple entities leads to confusion.
Global names should be unique across its scope. You used the name images  defined as const images = {}; but in parts of the code you also use the name images to represent an array. So you will have to be checking is this the images in global scope, or the images as an array.
Also image is used to represent an Image in some places and an image description in other places, confusing...
General comments

Use strict mode it will result in better code and runs faster which is good for games. Add "use strict"; to the top of the JS file.

Don't forget semicolons

Don't create blockless blocks

//bad
for (const image of images)
    loadImage(image.url, image.name, onImageLoaded)

// good
for (const image of images) {                         // define block start
     loadImage(image.url, image.name, onImageLoaded); // semicolon
}                                                     // define block  end

You are not using standard export so that means the whole set of functions could be in global scope. Use a singleton or use the native export. Try to limit your exports, exporting every function is just a pain an will lead to problems.

The function getTileCoordinates is out of place and does not belong here. BTW there is a better way to find the row

function getTileCoordinates(image, index, width, height){
    const tilesAcross = image.width / width | 0; // | 0 floors result
    return {
        x : width * (index % tilesAcross),
        y : (index / tilesAcross | 0) * height
    };
}

Don't repeat. The functions downloadSprites and downloadTiles are repeats

I could not work out why you are returning the result of the load callbacks. There is no consistency as you do it sometimes and other times not. Also you are passing the image as an argument to the callbacks but there is no indication that you use it. For the onload event you can access the image via this if needed. Note you will have to use a standard function declaration for the callback.

There is no error checking. What do you do if the connection or a request is lost?

A rewrite
This is how I would have written your code. It is just a suggestion example and far from ideal. I do not know what you wanted exposed but I only exposed what was not called internally (assuming this is a module)
"use strict";
const images = {
    tiles : {},
};

function loadImage(imageDesc, onLoad) {
    var image = images[imageDesc.name];
    if (image) { onLoad() }
    else{
        image = images[imageDesc.name] = new Image();
        image.src = imageDesc.url;
        image.onload = onLoad;
    }
},

function loadImages(imageArray, onAllLoaded) {
    var imagesLoaded = 0;
    const onLoad = () => {
        if (imageArray.length === ++ imagesLoaded) { onAllLoaded() }
    }
    for (const imageDesc of imageArray) { loadImage(imageDesc, onLoad) }
},

function loadList(type, list, onLoad) {
    loadImages(
        list.map(imageDesc => {
            const name = `${type}_${imageDesc.id}`;
            return  { name, url : `assets/${type}/${name}.png` };
        }),
        onLoad
    );
},

const assests = {
    images,
    loadTiles(tiles, onLoaded) {
        loadList("tiles", tiles, onLoaded);
    },
    loadSprites(sprites, onLoaded) {
        loadList("sprites", sprites, onLoaded);
    },
    loadJSON : (url, name) => fetch(url, { method: 'GET' }).then(response => response.json()),
};

export default assests;


First lets split up the query so we can read it:

var alertList = from alerts in _db.Alerts.AsNoTracking()
                where alerts.AlertID >= Id.AlertID && alerts.DataWystapienia >Id.DataWystapienia
                select new MyAlerts { AlertID = alerts.AlertID, DataWystapienia = alerts.DataWystapienia, Message = alerts.Message };

var subAlertList = from subAlerts in _db.SubAlerts.AsNoTracking()
                   where subAlerts.AlertID >= Id.AlertID && subAlerts.DataWystapienia > Id.DataWystapienia
                   select new MyAlerts { AlertID = subAlerts.AlertID, DataWystapienia = subAlerts.DataWystapienia, Message = subAlerts.Message };

var myAlertsList = alertList.OrderByDescending(a => a.AlertID).Take(Id.NumberOfRows)
                   .Concat(subAlertList.OrderByDescending(a => a.AlertID).Take(Id.NumberOfRows))
                   .OrderByDescending(a => a.AlertID).Take(Id.NumberOfRows);

this is fully equivalent to your code I only extracted the 2 lists

the last operation of code has 3 OrderByDescending(a => a.AlertID).take(Id.NumberOfRows) while only 1 is needed

var myAlertsList = alertList.Concat(subAlertList).OrderByDescending(a => a.AlertID).Take(Id.NumberOfRows);


Listner needs a virtual destructor
and the OnEvent() method should probably be pure virtual:

class Listener
{
public:
    virtual void OnEvent(Event& event, Dispatcher& sender) {};
};

// Try

class Listener
{
    public:
        virtual ~Listener() {}
        virtual void OnEvent(Event& event, Dispatcher& sender) = 0;
};

You need the virtual destructor because delete will more than likely be called via a pointer to the base class (Listener) at some point.

No point in implementing OnEvent() to do nothing if you need sombody to over-ride it.

Personally I would prefer to use boost::ptr_vector<> rather than a std::vector<std::shared_ptr<>>. The boost vector has a couple of advantages (less lcoks required). Also its members are provided via references rather than pointers so it makes it more natural to use with the standard algorithms (not such a big deal in C++11 (with lambdas) but it makes C++03 much easier to use).

typedef std::shared_ptr<Listener> ListenerPtr;
typedef std::vector<ListenerPtr> Listeners;
Listeners _listeners;

// Replace with:

boost::ptr_vector<Listener>  listeners;

Be careful of using '_` on the front of identifiers. The rules are not obvious so best avoided to make sure you don't actually break them. Underscore Rules

Personally not a fan of the following:

   if( _listeners.end() != std::find(_listeners.begin(), _listeners.end(), listener) )

Nothing wrong with it. But reversing the order of the test just makes you pause a second. See Yoda Conditionals.

Prefer to use standard algorithms rather than hand coded loops.

   for( Listeners::iterator iter = _listeners.begin(); iter != _listeners.end(); ++iter )
        (*iter)->OnEvent(event, *this);

   // Try
   std::for_each(listeners.begin(), listeners.end(),
                 std::bind2nd(Listner::OnEvent, event)
                ); // Assume boost::ptr_vector<>

   // Or go all C++11 on us
   std::for_each(std::begin(listeners), std::end(listeners),
                 [&event](std::shared_ptr<Listener>& lis) {lis->OnEvent(event);}
                );

If you want to have listeners that only deal with a specific type of event. You can write your Listner to be a filtering lsitener.

class Listener
{
public:
    virtual void OnEvent(Event& event, Dispatcher& sender) {};
};

Change to:

template<class ForEvent>
class Listener
{
    public:
        ~Listener() {}

        // This is the method called by the dispatcher.
        void eventFilter(OnEvent& event, Dispatcher& sender)
        {
             // dynamic_cast to a pointer type.
             // Result is NULL if not the correct type.
             // If you used a value type then it would throw an exception.
             ForEvent* specialEvent = dynamic_cast<ForEvent*>(&event);
             if (specialEvent != NULL)
             {
                 // Only call the OnEvent for the types we want.
                 // put back to a references (so OnEvent does not need to
                 // check for NULL).
                 this->OnEvent(*specialEvent, sender);
             }
        }

        virtual void OnEvent(ForEvent& event, Dispatcher& sender) = 0;
};


Let's see what is the Big O of your code.

In new versions of Java substring creates a new String and performs in \$O(n)\$ (In older versions this is \$O(1)\$)
uniqueRepeats.contains(character) results in \$O(m)\$ where \$m\$ is count of unique characters.
restOfString.indexOf(character) != -1 - this is again \$O(n)\$
uniqueRepeats += character Depending on the JVM this might end up creating set of StringBuilder objects or set of String objects that are discarded. So this is probably \$O(m^2)\$
You are doing this for \$n\$ characters.

So time complexity is - \$O(n *(n + m + m^2))\$ in some situations \$m\$ can be as large as \$n\$. So if we simplyfy things we get \$O(n^3)\$.

Ideas:

This is where your HashMap idea would've been better. We can simply store Char and an Integer count. Then iterate over your map to count all elements that has more than \$1\$ element. LinkedHashMap is very useful for a situation like this.
Why is LinkedHashMap better? Because it has an internal linked list that allows faster iteration.
We can also use an array if this is ASCII only. (But it is easier with a Map).
This will result in armotized \$O(n)\$. Which is lot better.
Either way all these are theoretical and it is always better to profile things.

Code

//Will keep track of unique repeats.
//Convert single char to String to be used in method.
//If not in uniqueRepeats, check if it is a repeat.
//If it is a repeat, increase count and concat it to uniqueRepeats

You have mentioned what you are doing in comments. We can also understand that from code itself. So it is better to include why comments.
I recommend that you use an IDE to indent code. Code is clearly not indented accurately.

if(!uniqueRepeats.contains(character)) {
    if(restOfString.indexOf(character) != -1) {

Be consistent. We can use contains to both above statements.

References

https://stackoverflow.com/a/1532483/1355145
http://java-performance.info/changes-to-string-java-1-7-0_06/
https://stackoverflow.com/questions/26311776/why-iteration-through-buckets-in-linkedhashmap-is-faster-than-hashmap


Let me collect a couple of thoughts here.

Aggregate initialization currently works like this:

array2d<int, 2, 2> a{{1, 2, 3, 4}};

but wouldn't it be favorable to allow for

array2d<int, 2, 2> a{{1, 2}, {3, 4}};

std::array::at performs bound checking and throws upon an out of bounds index. When your intention is to stick with the std::array interface, you should do the same.
If you want the container to be standard-compliant, there are some type aliases missing and maybe more. In particular, there are no cbegin(), cend(), crbegin(), crend() member functions. Is this intended?
You implicitly use row-major order. Are you sure everyone expects this? Users familiar with Eigen and their fixed size matrices might at least want to customize row-/column-major ordering, e.g. Eigen::Matrix<int, 2, 2, Eigen::ColMajor> m;
A range based for loop will considerably differ from a manual loop over rows and columns. Example:

// Loop over elements, transposed access. Requires nested loop.
for (std::size_t i = 0; i < 2; ++i)
   for (std::size_t j = 0; j < 2; ++j)
      std::cout << a[j][i] << "\n";

// Loop over elements, tranposed access impossible. Only one loop.
for (const auto& i : d)
    std::cout << i << "\n";

This is slightly unintuitive. Shouldn't the range based for loop require a nested loop as well?
The static data member sizes is not used anywhere.

Getting a two-dimensional array to work is not that much of an effort. Getting the semantics right is hard. Sticking to the std::array interface is a good goal when ease of use is intended for those familiar with the std::array template. But the additional dimension pulls in requirements that can't be tackled with the concepts of std::array. I would recommend having a look at established linear algebra libraries and their fixed size matrices. Also, the mdspan proposal for a multi-dimensional view on array types might be a good read.


Function to test if exactly one of three parameters is truthy, without using equality operators

You don't need to count the falsy arguments.  The challenge only asks you to count the truthy ones.  Since true is treated as 1 by the + operator, you can use that to perform the count.

As for the prohibition on using equality operators, you can easily work around that using two inequalities.

You forgot to declare output, so that was treated as a global variable.

function onlyOne(a, b, c) {
    let truthyCount = !!a + !!b + !!c;
    // Workaround for the prohibited test truthyCount == 1
    return 0 < truthyCount && truthyCount < 2;
}

console.log("These should be true:");
console.log(onlyOne(true, null, undefined));
console.log(onlyOne(false, '', '0'));
console.log(onlyOne(false, 0, '0'));
console.log(onlyOne(false, [], null));
console.log(onlyOne(1/0 /* Infinity */));

console.log("These should be false:");
console.log(onlyOne(1, 'a', Infinity));
console.log(onlyOne(false, null, undefined));
console.log(onlyOne(false, NaN, null));
console.log(onlyOne(0));

Based on @Blindman67's suggestion, here's another solution, which involves fewer operations.  How it works is less obvious from inspection, though.  Basically, it tests whether the number of falsy parameters is 2.

function onlyOne(a, b, c) {
    return !((!a + !b + !c) - 2);
}

console.log("These should be true:");
console.log(onlyOne(true, null, undefined));
console.log(onlyOne(false, '', '0'));
console.log(onlyOne(false, 0, '0'));
console.log(onlyOne(false, [], null));
console.log(onlyOne(1/0 /* Infinity */));

console.log("These should be false:");
console.log(onlyOne(1, 'a', Infinity));
console.log(onlyOne(false, null, undefined));
console.log(onlyOne(false, NaN, null));
console.log(onlyOne(0));


More things that can be improved:
Variable declarations
To allow for easier understanding you should declare variables as close as possible to their usage (even though it's semantically no different)
Additionally IIRC javascript variables are usually camelCase and not snake_case. Furthermore it's useful to write out variable names instead of shortening them as much as possible. This reduces cognitive load and makes the code easier to read.
General case
Simply through the way your code works, I'm dead sure that you don't even need that if-statement you have there. It's superfluous, because it's already working for the general case. If your nodes have 0 elements, the for-loop is not executed and the "recursion bottom" is reached.
"Final" result:
function uncheck_all_tree (nodes) {
    for (var i = 0, length = nodes.length; i < length; i++) {
        uncheck_all_tree(nodes[i].children);
        var node = tree.jstree('get_node', nodes[i]);
        var nDomElement = document.getElementById(n.id + '_anchor');
        if (nDomElement !== null) {
            console.log(node.id + '_anchor');
            nDomElement.className = 'jstree-anchor';
        }
        node.state.checked = false;
    }
}

In addition to that Ismael Miguel has suggested in a comment to use Array.forEach.call(nodes[i].children, function(node) { [...] }); to further improve performance. More information on how that works can be found at the MDN Documentation


Modify XML attribute based on element value

Performance

The most obvious improvement would be to only save the file once, after you've made all the necessary changes.
You're also doing a lot of duplicate regex matching. The Where calls do matching, and then the foreach loops have to look for the same matches again. There's also some overlap between the single and multiple match logic

All of that can be simplified into a single foreach loop:

// read file content

foreach (var formulaNode in xdoc.Descendants("disp-formula"))
{
    var matches = regex.Matches(formulaNode.Value);
    if (matches.Count == 0)
        continue;

    var id = "deqn" + matches[0].Value;
    if (matches.Count > 1)
        id += "-" + matches[matches.Count - 1].Value;

    formulaNode.Attribute("id").Value = id;
}

// save file

Do you have a specific reason for using a lookbehind and lookahead in your regex? \\tag\{(\w+)\} will be faster. The match value no longer contains just the tag ID, but because you're using a capture group it's still easy to obtain that ID: match.Groups[1].Value.
Instead of using Count(), you can use an array's Length property directly. Count() is a Linq method, and for arrays it'll just return their Length, but it does have to do some type checking, so it takes a tiny bit of extra work.

Code quality

The filename is duplicated several times. Duplication makes code harder to maintain. Store the filename in a variable, or better: make it a method parameter.
Variable naming is a little inconsistent (camelCase, _leadingUnderscore, _PascalCase). camelCase is normally used for parameters and local variables, PascalCase for type, property and method names. Some people use leading underscores for private fields, others don't - but whatever approach you pick, being consistent will make your code easier to read and understand.
Some variable names are rather undescriptive: p, x, y. Something like tagIDs, firstTagID and lastTagID would make the code easier to understand.

Other

The multi-match logic only looks at the first and last tag IDs. Does your input always contain sequential tag IDs, or could they come in a different order or contain 'gaps'? You may want to document this assumption - if you ever need to modify this code later on then at least you'll know what you were thinking back then.


Basically you need to remove the unused fopen() call and change ponderous operators to handy ones as for some reason you made a peculiar choice in favor of the former, like for vs. foreach, array_push vs simple assignment, etc. Also consider a cleaner way to output HTML

<?php
$pattern = "domain/folder/*.*";
$files = glob($pattern);

// loop over all the files, saving their contents and ids to arrays

$contents = [];
$titles = [];
$ids = [];
foreach ($files as $filename)
{
    $data = file_get_contents($filename);
    $contents[] = $data;

    preg_match('#<title>(.*?)<\/title>#', $data, $match);
    $titles[] = $match[1];

    $ids[] = preg_split('#( |-|,)#', $match[1])[0];
}
?>

<?php foreach ($titles as $x => $title): ?>

<a href="#<?=$ids[$x]?>"><?=$title?>

<?php endforeach ?>

<?foreach ($contents as $x => $content): ?>
    <div id="<?=$ids[$x]?>"><?=$content?>

<?php endforeach ?>