Method for obtaining adjacent chunk positions

Well, I suggest next approach

        if (tileX != 0 && tileY != 0 && tileX != chunkSize - 1 && tileY != chunkSize - 1)
        {
            return;
        }

        var leftChunk = tileX == 0;
        var rightChunk = tileX == chunkSize - 1;
        var downChunk = tileY == 0;
        var upChunk = tileY == chunkSize - 1;

        if (leftChunk)
        {
            chunksToUpdate.Add(new Vector3Int(position.X - chunkSize, position.Y, position.Z)); // Left
            if (downChunk)
            {
                chunksToUpdate.Add(new Vector3Int(position.X - chunkSize, position.Y - chunkSize, position.Z)); // DownLeft
            }
            else if (upChunk)
            {
                chunksToUpdate.Add(new Vector3Int(position.X - chunkSize, position.Y + chunkSize, position.Z)); // UpLeft
            }
        }
        else if (rightChunk)
        {
            chunksToUpdate.Add(new Vector3Int(position.X + chunkSize, position.Y, position.Z)); // Right
            if (upChunk)
            {
                chunksToUpdate.Add(new Vector3Int(position.X + chunkSize, position.Y + chunkSize, position.Z)); // UpRight
            }
            else if (downChunk)
            {
                chunksToUpdate.Add(new Vector3Int(position.X + chunkSize, position.Y - chunkSize, position.Z)); // DownRight
            }
        }
        if (downChunk)
        {
            chunksToUpdate.Add(new Vector3Int(position.X, position.Y - chunkSize, position.Z)); // Down
        }
        else if (upChunk)
        {
            chunksToUpdate.Add(new Vector3Int(position.X, position.Y + chunkSize, position.Z)); // Up
        }

It makes code a little bit more readable by using bool named variables and also has less code lines and if else branching.

Moreover, it is often (almost every time) better to have less nesting via inverting if statement like I did. So basically I quit if it is not an edge tile.


I think you are overcomplicating the problem. I would probably go with a proper Markdown parser (like mistune), or parse the generated HTML instead. Here is how I would do it using BeautifulSoup parser:

from pprint import pprint

from bs4 import BeautifulSoup
import requests

response = requests.get("https://docs.python.org/3.6/reference/index.html")

soup = BeautifulSoup(response.content, "html.parser")
contents = soup.select_one("#the-python-language-reference ul")

pprint({
    li.a.get_text(): [li.a.get_text() for li in li("li")]
    for li in contents.find_all("li", recursive=False)
})

Prints:

{'1. Introduction': ['1.1. Alternate Implementations', '1.2. Notation'],
 '10. Full Grammar specification': [],
 '2. Lexical analysis': ['2.1. Line structure',
                         '2.2. Other tokens',
                         '2.3. Identifiers and keywords',
                         '2.4. Literals',
                         '2.5. Operators',
                         '2.6. Delimiters'],
 '3. Data model': ['3.1. Objects, values and types',
                   '3.2. The standard type hierarchy',
                   '3.3. Special method names',
                   '3.4. Coroutines'],
 '4. Execution model': ['4.1. Structure of a program',
                        '4.2. Naming and binding',
                        '4.3. Exceptions'],
 '5. The import system': ['5.1. importlib',
                          '5.2. Packages',
                          '5.3. Searching',
                          '5.4. Loading',
                          '5.5. The Path Based Finder',
                          '5.6. Replacing the standard import system',
                          '5.7. Special considerations for __main__',
                          '5.8. Open issues',
                          '5.9. References'],
 '6. Expressions': ['6.1. Arithmetic conversions',
                    '6.2. Atoms',
                    '6.3. Primaries',
                    '6.4. Await expression',
                    '6.5. The power operator',
                    '6.6. Unary arithmetic and bitwise operations',
                    '6.7. Binary arithmetic operations',
                    '6.8. Shifting operations',
                    '6.9. Binary bitwise operations',
                    '6.10. Comparisons',
                    '6.11. Boolean operations',
                    '6.12. Conditional expressions',
                    '6.13. Lambdas',
                    '6.14. Expression lists',
                    '6.15. Evaluation order',
                    '6.16. Operator precedence'],
 '7. Simple statements': ['7.1. Expression statements',
                          '7.2. Assignment statements',
                          '7.3. The assert statement',
                          '7.4. The pass statement',
                          '7.5. The del statement',
                          '7.6. The return statement',
                          '7.7. The yield statement',
                          '7.8. The raise statement',
                          '7.9. The break statement',
                          '7.10. The continue statement',
                          '7.11. The import statement',
                          '7.12. The global statement',
                          '7.13. The nonlocal statement'],
 '8. Compound statements': ['8.1. The if statement',
                            '8.2. The while statement',
                            '8.3. The for statement',
                            '8.4. The try statement',
                            '8.5. The with statement',
                            '8.6. Function definitions',
                            '8.7. Class definitions',
                            '8.8. Coroutines'],
 '9. Top-level components': ['9.1. Complete Python programs',
                             '9.2. File input',
                             '9.3. Interactive input',
                             '9.4. Expression input']}

Note that this would work for the limited depth of the nested lists. If it would be needed, you can generalize parsing the nested lists using something like this dictify() function.


As the comments say, it's not clear what the if($(parent).is(this.rootSelector)) checks are for. You only use one this property - this.root - would it be better to have a root variable and then two simple functions rather than prototype functions?

Your own improvements are better, but they can be improved more by returning earlier. You started doing that with the return null;, but you can do it with all the values, avoiding all local variables and reducing your code indentations. I have also made your code consistently use brackets after all control structures.

//returns previous element in a depth-first search traversal
//returns null if at the start of the tree
TreeWalker.prototype.getPreviousElement = function(element) {
  if (element.previousElementSibling === null) {
    if (element === this.root) {
      return null;
    }
    return element.parentNode;
  }
  element = element.previousElementSibling;
  while (element.children.length > 0) {
    element = element.lastElementChild;
  }
  return element;
};

//returns next element in a depth-first search traversal
//returns null if at the end of the tree
TreeWalker.prototype.getNextElement = function(element) {
  if (element.children.length > 0) {
    return element.children[0];
  }
  while (element.nextElementSibling === null) {
    element = element.parentNode;
    if (element === this.root) {
      return null;
    }
  }
  return element.nextElementSibling;
};


Simple singly linked list implementation in C

In terms for efficiency and concept, the implementation is fine.
It lacks the more interesting functionality such as deleting and inserting items.

The most important missing element is deleting the linked list itself:
when you allocate memory using malloc,
it's important to add functions to clean that up at some point.

Code duplication

In addElement,
the logic of creating a new element is duplicated twice.
This could be easily avoided by moving that logic to another function, for example:

struct Element * createElement(int value) {
    struct Element *newElement;
    newElement = malloc(sizeof(struct Element));

    newElement->value = value;
    newElement->nextElement = NULL;
    return newElement;
}

On closer look,
you didn't even really need an extra method,
you could eliminate the duplicated logic by moving the element creation before the if condition:

void add(struct LinkedList *list, int value) {
    struct Element *newElement = createElement(value);
    if(list->firstElement == NULL) {
        list->firstElement = newElement;
    } else {
        // ...
        lastElement->nextElement = newElement;
    }
}

Naming

Most of the names are good and nicely descriptive.
But there are a few exceptions:

getElement: despite its name, this function returns an int, not an Element. So getValue would be better.
lastElement as loop is not so great, as it's typically not referencing the last element. node would be a more common name for the purpose

Trivial simplifications

Some of the functions can be simplified very easily.

For example,
in getElement you really don't need the returnValue variable.
You assign to it right before you return it,
and that's the only use.
So avoid the pointless local variable.
Every variable has the potential of getting misused.
So if a variable has no good purpose to serve, then don't use it.

Another minor point is that instead of iteratedIndex = iteratedIndex + 1 you can write simply ++iteratedIndex.


Your code is indeed confusing, primarily because of the naming:

f should be firstPlayer, s should be secondPlayer and curSpeed should be speed or currentSpeed (it depends on whether there are other "speeds" to distinguish from).

Another remark: properties are UpperCamelCase so this

player_1.current.curSpeed

should be

player_1.Current.Speed


Here are a few lines that might be useful to add if you would like to use these options:

/**
 * Needed for SoftDelete to work
 */
$manager->setAttribute(Doctrine::ATTR_USE_DQL_CALLBACKS, true);

/**
 * Tell doctrine to look for custom ___Table classes in the models folder
 */
$manager->setAttribute(Doctrine::ATTR_AUTOLOAD_TABLE_CLASSES, true);


Build object from database without a discriminator column?

Here is your code refactored - since all animals have id, name and age, you can remove duplication (reading and setting these properties for each type of animal):

if (reader.HasRows)
{
    while (reader.Read())
    {
         string animalType = reader.GetString(3);

         Animal animal = CreateAnimal(animalType);
         animal.AnimalID = (int)reader["AnimalID"];
         animal.Name = (string)reader["Name"];
         animal.Age = (int)reader["Age"];
         list.Add(animal);
    }
}

Animal creation (if you are using type name as discriminator you can even use Activator.CreateInstance instead of this switch to create an instance of class):

private Animal CreateAnimal(string animalType)
{
     switch(animalType)
     {
        case "Dog": return new Dog();
        case "Cat": return new Cat();
        case "Mouse": return new Mouse();
        default:
             throw new ArgumentException();
     }
}


Irreversibly hash email addresses while preserving format/entropy

Test cases are very limited.  You might want to normalise equivalent addresses before hashing; for example, these addresses are all equivalent:

user@example.org
user@Example.Org
"user"@example.org

It's probably desirable that they hash to the same value.

Simply splitting on @ is naive - it's better to split on unquoted @, or more simply, just on the last @, given that DNS names don't contain @.

It's probably worth reading I Knew How To Validate An Email Address Until I Read The RFC.  After that, start looking for an email address parsing library for Python; I haven't used it, but it appears that Flanker will handle the parsing much more robustly than this code.


The trick to this challenge is to actually change the number into bit operations, and not to do string manipulation as you do. So here are some hints on how to do this to get you started:

Convert a binary string, text, of 0's and 1's into an int, use int(text, 2)
To clear a bit at a given offset, use n & ~(1 << offset)
To set a bit at a given offset, use n | (1 << offset)
To get a bit at a given offset (shifted down again to one bit), use (n & (1 << offset)) >> offset)

Combine these, and you'll get a fast enough solution.

Style review of current code

Some tips according to PEP8:

Use lower_snake_case for variable and function names -  This looks a little better, and wouldn't throw off the syntax highlighter here on Code Review either... :-)
Add a little vertical space in your code – Add two blank lines between functions, and add a blank line in natural segments within functions, like before if, else, for and while.
Put all top level code in a main() function – Try to only keep imports, constants and functions at the top level, and start your code using a if __name__ == '__main__':' followed bymain()`
Start using the print function, and str.format'ing– The % syntax will disappear some time, so start using the newer string formatting options already available.
For Python 2 and large \$n\$'s use xrange() in for loops – Using range() will create the entire list, whilst xrange() will create a generator, and only give you one element at a time. For large numbers this has a noticeable effect on memory and time performance
No need to create a list for join() – Instead of ''.join([ ... ]), you can simply use ''.join( ... ). The latter uses a generator instead of a list, similar to the range() vs xrange()

Refactored code running within time limit

So as not to spoil the fun for those wanting to solve this challenge by themselves, I've chosen to have the code hidden beneath a spoiler. That is if you hover over the block below you'll see the code.

  def getBit(n, offset):
    return (n & (1 << offset)) >> offset

def clearBit(n, offset):
    return n & ~(1 << offset)

def setBit(n, offset):
    return n | (1 << offset)

def changing_bits_challenge():

    n, q = map(int, raw_input().split())
    a = int(raw_input(), 2)
    b = int(raw_input(), 2)

    c = []
    for _ in xrange(q):
        words = raw_input().split()
        operator = words[0][4]
        bit_number = int(words[1])

        if operator == 'c':
            c.append(getBit(a+b, bit_number))

        if operator == 'a':
            a = clearBit(a, bit_number) if words[2] == '0'
                else setBit(a, bit_number)

        if operator == 'b':
            b = clearBit(b, bit_number) if words[2] == '0'
                else setBit(b, bit_number)

    print ''.join(str(i) for i in c)

changing_bits_challenge()


Reverse int within the 32-bit signed integer range

General comments

There is no reason to use a class. Instead, the functionality should be made into a free function.
Your code is overly complicated. There is no reason to make new string from which you erase characters one-by-one. Instead, you can convert the input integer to a string and use a standard function to reverse that.
Also, pay attention to const correctness. This protects from unintended mistakes and helps the compiler optimize more.

I would simplify your function to just:

int reverse(int i)
{
    try
    {
        auto reversed{ std::to_string(i) };
        std::reverse(reversed.begin(), reversed.end());

        const auto result{ std::stoi(reversed) };
        return i < 0 ? -1 * result : result;
    }
    catch (const std::out_of_range& e)
    {
        return 0;
    }
}

Further comments

If you want to have a fast solution, you should avoid std::string altogether. This you can do by "iterating" through the digits using arithmetic operations (division and modulus), as in (using std::string to only show you what is happening):

int x = 1234;
std::string s;

while (x > 0)
{
    s.push_back('0' + (x % 10));
    x /= 10;
}

std::cout << s << "\n"; // Prints 4321

I will let you take it from here to use these ideas to make your program even faster.
Regarding your theoretical question concerning complexity, if we assume that the input is treated as a string of n characters, there is \$\Omega(n)\$ lower bound by a trivial adversary argument. Basically, if you don't spend at least n time, you can't read the whole of the input, and then you cannot guarantee correct output on every instance.


I've found a way, it's not the best though. You can use nimble (Or async, it's basically the same but both larger in size and contain more functions) to do a series of functions, and then check from within the helper-class to see if a certain value has been set.

This is my new and improved version of the run-function:

db.prototype.run = function(callback){
    var self = JSON.parse(JSON.stringify(this));
    for(var key in this){
        if(typeof this[key] != "functions" && key != "dir" && key != "table") delete this[key];
    }
    helper.mkdb(self, function(err, created){
        helper.mktbl(self, function(err, created){
            self.docs = [];
            nimble.series([
                function(done){
                    if(!self.put) done(err, []);
                    else{
                        helper.put(self, function(err, docs){
                            self.docs = docs;
                            done(err, docs);
                        })
                    }
                },
                function(done){
                    if(!self.query && !self.find) done(err, self.docs || []);
                    else{
                        helper.find(self, function(err, docs){
                            self.docs = docs;
                            done(err, docs);
                        })
                    }
                },
                function(done){
                    if(!self.pluck) done(err, self.docs || []);
                    else{
                        helper.pluck(self, function(err, docs){
                            self.docs = docs;
                            done(err, docs);
                        })
                    }
                }
            ], function(err, res){
                callback(err, helper.lastData(res));
            })
        })
    });
}


Avoid global variables

There's no good reason for the variables classes and grades to be defined and manipulated in global scope.
For example, it would be better to pass grades into the calculate function as a parameter.

Consider a table-driven solution

The long if-else chain is tedious.
You could instead use a dictionary to map the grade notes to scores:

score_map = {
    'A': 4,
    'C': 2,
    'C-': 1.7,
    'D': 1,
    # ... and so on
}
total = 0
for grade in grades:
    total += score_map[grade]

This approach also makes it easy to use a list-comprehension that's more compact than a for loop:

return sum(score_map[grade] for grade in grades) / 6

Usability

Making the user enter the class names seems rather pointless.
The program simply prints them back, without doing anything interesting with them.

Style

The parentheses are redundant here:

while (y <= 5):

Instead of y = y + 1 you can use the augmented assignment form y += 1.

Python has a style guide called PEP8 with a utility to spot such issues.


Updated:

formatDate = (date) ->
  timeStamp = [date.getFullYear(), (date.getMonth() + 1), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()].join(" ")
  RE_findSingleDigits = /\b(\d)\b/g

  # Places a `0` in front of single digit numbers.
  timeStamp = timeStamp.replace( RE_findSingleDigits, "0$1" )
  timeStamp.replace /\s/g, ""


I think that the call to argp_parse() in hcv_parse_program_arguments() is missing a pointer to the arguments struct. Looking at the main() function in the canonical Argp Example 3, we see that the argp_parse() function is passed a pointer to struct arguments arguments.

int
main (int argc, char **argv)
{
  struct arguments arguments;

  /* Default values. */
  arguments.silent = 0;
  arguments.verbose = 0;
  arguments.output_file = "-";

  /* Parse our arguments; every option seen by parse_opt will
     be reflected in arguments. */
  argp_parse (&argp, argc, argv, 0, 0, &arguments);

  printf ("ARG1 = %s\nARG2 = %s\nOUTPUT_FILE = %s\n"
          "VERBOSE = %s\nSILENT = %s\n",
          arguments.args[0], arguments.args[1],
          arguments.output_file,
          arguments.verbose ? "yes" : "no",
          arguments.silent ? "yes" : "no");

  exit (0);
}


You could simplify your code to look something like this (warning: I didn't test my code, so you should double-check to make sure it functions identically to the original)

days_map = {
    "monday": mon,
    "tuesday": tues
}

day = days_map[cd]
if cp == "0":
    print(day.values()[0])
else:
    print(day[int(cp)])

Several notes:

In your code, you use a while loop, but in every case, immediately break out of it, either by literally using break or by making the conditional false. What you want instead is an "if" statement. However, because the "if" statements are almost identical, you can simplify it completely by replacing it with a call to a dict.

(In case you aren't familiar with what dicts are, they're really nifty data structures that make life insanely easier. As you can see, they helped turn a large chunk of code into just 10 or so lines! Here's a link to CodeAcademy which gives an introduction to them))

I'm assuming that mon and tues are dicts of some kind -- I made another dict (days_map) to refer to them. This is a common technique in Python -- whenever you have a large amount of if and elif statements, check to see if you can somehow fold things into a dictionary so you can need to make only a single call.

Your for loop is also redundant. If you have a break immediately after, then it's equivalent to simply printing the first value.


This is a decent start. Here are some things that could be improved.
Naming
Your variable names are single letters that as far as I can tell have no relationship to what they represent. The variable x is the number of test cases to run. You should name it numTestCases or testCases. q is the specific test case you're currently running, so testCase or testCaseIndex would be a better name. n is the number of inputs to read, so numInputs would be a good name. And arr tells us very little other than that it is an array. How about inputs? I would rename i to inputIndex, as it's for iterating over the inputs. d could be outputIndex.
Functions
There are 4 different things your code does:

Reads the inputs from the user (or stdin)
Finds duplicate items in the array and combines them
Moves 0s to the end of the array
Prints the results

Each of those should be a different function with a clear name.
Space Efficiency
You have an array declared as int arr[100000]. Assuming a typical 32-bit int implementation, that's ~400k. On my system, the default stack size is 1MB. That means that single array takes up half the stack. If had just two more of those, you'd get a stack overflow just running the app. Since it's only 1 allocation at the start of the program and not a repeating allocation, I recommend using malloc() to allocate the array and freeing it after you've finished.
Time Efficiency
The main slowdown in your code is the part that copies the remaining elements when you find a 0 in the array. There are built-in functions in the standard library to do this task for you. In this case, this loop:
            for(m=0;k+m+1<=j;m++)
            {
                arr[k+m]=arr[k+m+1];
            }

can be replaced with a single line:
            memmove(&arr[k], &arr[k+1], sizeof(arr[0]) * (j - (k + 1) + 1));

This is significantly more efficient. The library function (which is sometimes not even a function), can use SIMD instructions, and other speedups to make it much faster than you're likely to do on your own. And it's portable. When I run the test with just that single change, it passes.
There are other ways you could speed this up, too. Instead of copying the remaining portion of the array at every 0, you could read up to the first 0. Mark that index. Read up to the next 0. Move only the values between those 2 indexes back, and repeat. This way you never move any element in the array more than once.


Fill missing dates into array of np.datetime

As you will be able to see from your provided sample input, your code does not produce the intended result. Here is a minimal example:
dates = np.arange(np.datetime64('2018-02-01'), np.datetime64('2018-02-05'), 2)
stride = (dates[1] - dates[0])
result = np.arange(np.datetime64(dates[0]), np.datetime64(dates[-1] + stride))

print(dates)   # > ['2018-02-01' '2018-02-03']
print(result)  # > ['2018-02-01' '2018-02-02' '2018-02-03' '2018-02-04']

result includes 2018-02-04, which is outside of the range of dates. This is only the simplest case for which this code fails, it will also fail for input arrays that are not sorted in ascending order. The only case your code would cover correctly is an input array of continuous dates (sorted in ascending order). There are two central errors in your code:

We do not need stride
We want the output range to include everything up until and including the maximum value of our input array. Since the stop argument to numpy.arange is exclusive, we need the following:
stop:
maximum of input array + 1

last element of output array:
(maximum of input array + 1) - 1
= maximum of input array

Your current implementation does the following:
stop:
maximum of input array + stride

last element of output array:
(maximum of input array + stride) - 1

The larger the difference between dates[0] and dates[1] (= stride), the more undesired values will be contained at the end of our output array.

The maximum is not always the last element
So we need to access the input array's maximum value to get the correct stop argument for numpy.arange. This will only be the last element if the input array is sorted in ascending order or if we get rather lucky, both cases are not specified by the problem statement.

Correcting these two errors will give us this simple implementation:
def make_continuous_sorted(np_array):
    return np.arange(np.min(np_array), np.max(np_array) + 1)


The way you're doing it has advantages over a session based redirect because you have the ability to link people directly to that login with redirect URL.

The disadvantage is phishing as you pointed out.

http://www.mysite.com/login.php?dest=http://mysite.phishing.com/

The way you're doing this, using $_SERVER['REQUEST_URI'] means you expect the $_GET['dest'] to only include a path, not a domain.

So you could add a check in the login page where it sets the $dest

$dest = "./";
if(isset($_GET["dest"]))
{
    $parts = parse_url( $_GET['dest'] );

    // if there is no `host` key set in the parse_url array, then its an internal path
    // so set the new $dest
    if( !isset( $parts['host'] ) )
    {
        $dest = $_GET["dest"];
    }
}


Build Excel formulas with string replacements

I'm not even going to review the C#, because there's a far better way to do the Excel portion.

Instead of creating this enormous formula (which I hope you don't need anymore nested IF portions, you've hit Excel's limit of 7), you can create a table that has the formula properties in it, then lookup what's in that table.

So, let's create our formula table/area:

---L---+--M--+---N---
Level  |Rate |Add
      0| 0.05|      0
  10000|  0.1|    500
  30000| 0.15|   2500
  70000|  0.2|   8500
 140000| 0.25|  22500
 250000|  0.3|  50000
 500000| 0.32| 125000

So, with that, we can build our actual formula:

=(J1-INDEX(L:L,MATCH(J1,L:L,1)))*INDEX(M:M,MATCH(J1,L:L,1))+INDEX(N:N,MATCH(J1,L:L,1))

If you're not an Excel whiz, here's what's happening:

The INDEX(...) function in a formula will do a lookup on the first value in a column that matches a specific location. So, INDEX(L:L,1) will return the value in L1. Simple enough.

Next, MATCH(...) is a function that will find the first value in a column that is less than, equal to or greater than the provided value. So MATCH(J1,L:L,1) will find the index of the cell that is the last cell found which is less than (the final 1 parameter) our current cell. So from our L column, for 1 it finds 0, etc. It then returns the row that cell is on, which can be piped to INDEX to find the actual value in that cell (or a different column).

So when we put it together, assuming J1 is 100000, we're replacing our formula with:

=(100000-70000)*0.2+8500

Which gives us 14,500, the exact value your formula gives us.

Some bonuses of this version:

Shorter, more concise formula. Easy copy/paste, easy to change the values later. (Suppose the criteria for 70000 become 65000, easy to change.)
More descriptive information, adding values is a piece of cake (and requires 0 work from the programmer).
Doesn't require a C# programme to pre-fill the spreadsheet. (That's a huge bonus right there.)
Makes you look like a boss being able to show the business guys how this stuff works.
Less typing in the future.

These are not mutually exclusive items.


I really think your code is having at least two issues. The first one is something that may confuse your service consumers a lot. The second one is probably a bug.

Careful With Status Codes

.catch(function(err){
  res.status(400).send("Couldnt update question")
})

This is not following RESTful approach. This .catch will be invoked if your code could not update a question. Meaning, the service was not able to fulfill a request. The correct HTTP response code for such situation is 500 Internal Server Error.

You should only return 400 Bad Request if the request was validated and there were issues with the payload (request body received). In such case, HTTP 400 is truly the best option, but in order to improve user experience, you should also provide the information about what exactly was wrong with the request. E.g. HTTP 404 + response payload

{
  "error": {
    "referenceId": "TOO_LONG_QUESTION",
    "description": "Question payload should not exceed 1024kb, however received 2048kb."
  }
}

The response format is actually arbitrary. Just think about what would be useful for a developer to know so that they can start troubleshooting in a right place.

Possible Bug

I numbered the code lines to make it easy to refer to them.

( 1)  collection.update({
( 2)    "synonyms._id": new ObjectId(subId)
( 3)  },
( 4)    {
( 5)        $set: {"synonyms.$.text": newArray}
( 6)    }
( 7)  ).then(function(doc){
( 8)    return updateVersions(dialogName).then(function(){
( 9)        console.log('version updated')
(10)    })
(11)    .catch(function(err){
(12)        console.log('version not saved')
(13)    })
(14)  }).then(function(doc){
(15)    res.status(200).end()
(16)  }).catch(function(err){
(17)    res.status(400).send("Couldnt update question")
(18)  })

If versionCollection.update(...) in updateVersions(...) fails, the promise will be rejected and we will fall into lines 11-13 which is good. There is one problem though... The promise created in line 1 (collection.update(...)) will NOT fail even though we failed to update the versionCollection. Try debugging it and you will see what I mean.

I think, what you need to do there is to re-throw the error like this:

(11)    .catch(function(err){
(12)        console.log('version not saved');
(12')       throw err;  <<-------------------------
(13)    })

Asynchronosity Is NOT Easy

Yes, it's not easy at all. Even with promises. I really recommend you to read about await/async feature of ES2017 which simplifies things a lot.

With await/async your code would look much more "regular" imperative code. It reads as synchronous but acts asynchronously. Here's a sketch (not a 100% working code):

router
  .post('/:dialogName', async (req, res) => {
    const dialogName = req.params.dialogName;
    const collection = db.get().collection(dialogName);

    try {
      const doc =  await collection.update(
        { "synonyms._id": new ObjectId(req.body.subID) },
        { $set: {"synonyms.$.text": req.body.newArray} }
      );

      try {
        await updateVersions(dialogName);
        console.log('version updated');
      } catch (err) {
        console.log('version not saved');
        throw err;
      }

      res.status(200).end();
    } catch {
      res.status(400).send("Couldnt update question");
    }
  })


I have a program that seems to work and produce the same results as your own code. However I have a problem in that the intron doesn't seem to be defined properly

Suppose my sequence is the alphabet and the exons we have are defined by

@beginning_exons = (5, 17);
@end_exons       = (12, 21);

                  1                   2
1 2 3 4|5 6 7 8 9 0 1 2|3 4 5 6|7 8 9 0 1|2 3 4 5 6
A B C D|E F G H I J K L|M N O P|Q R S T U|V W X Y Z
        [=============] <-----> [=======]

so they are EFGHIJKL and QRSTU, forming an intron MNOP. The calculation in your program, and in my code that produces the same result, gives $end = 'MN', which is fine, but $beginning = 'PQ', which I don't understand. It is the last character of the intron and the first character of the exon

Can this be right? I have put exactly the values above into your code and mine and get the same result

Update

As usual, the solution was staring me in the face. I am confident that the values you extract to @beginning_exons and @end_exons are not character positions but offsets, that may be passed directly to substr. It was your comment "subtract 1 from end of exon because its 1-based index" that threw me

So it is the gaps between the letters that are numbers from zero at the start of the string. Like this

                    1                   2
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6
 A B C D|E F G H I J K L|M N O P|Q R S T U|V W X Y Z
         [=============] <-----> [=======]

Now the "exon" EFGHIJKL starts at 4 and ends at 12, and QRSTU starts at 16 and ends at 21, making the data look like this

@beginning_exons = (4, 16);
@end_exons       = (12, 21);

Assuming this makes the arithmetic much easier, because there is no off-by-one error to account for, and the start and end of the intron are 12 and 16—the end of the first exon and the beginning of the next. Furthermore, numbers can be fed directly into substr without any offset, except that the last two characters of the intron are clearly at (6-2)

I've modified my code below to take this into account, and it makes it much clearer to read

Here's my solution

The main reason yours is so slow is that it's reading the HG38 file line by line, which means it has to upper case each line and append it to the sequence up to 4 million times per sequence

That's very slow because the repeated appending will mean that the string will frequently become too big for the space allocated to it, and it has to be copied to a larger space before it can be expanded. Copying such a huge string thousands of times takes a lot of processor work

I have written it so that a whole chromosome is read at a cctime. Then all that has to be done is to remove the newlines and set it to upper case, just once

I've also printed the each chromosome's name when it is encountered, to give some confirmation that the process is progressing. (You can stop this by removing the print "    $key\n" statement.) The time taken to test the introns at the end is minimal

As I said, this code produces the results 492784 /499504 that you expect, but I'm still concerned about the end pair of bases. Please let me know if you have an explanation

use strict;
use warnings FATAL => 'all';

STDOUT->autoflush;

my ( $ref_gene_file, $hg38_file ) = qw/ refGene.txt hg38.fa /;

my %chromosome;

{
    print "Processing HG38:\n";

    open my $hg38_fh, '<', $hg38_file or die qq{Error opening "$hg38_file" for input: $!};

    local $/ = '>';

    my $key;

    while ( <$hg38_fh> ) {

        next unless /[^>\s]/;

        s/(.+)// and $key = $1;
        printf "    %s\n", $key;

        $chromosome{$key} = uc tr/A-Za-z//cdr;
    }

    print "\n";
}

my $total_introns = 0;
my $GUAG_introns  = 0;

{
    open my $ref_gene_fh, '<', $ref_gene_file
            or die qq{Error opening "$ref_gene_file" for input: $!};

    while ( <$ref_gene_fh> ) {

        my @column = split;

        my ( $chr, $sense, $n, $exon_starts, $exon_ends ) = @column[ 2, 3, 8, 9, 10 ];
        my @exon_starts = $exon_starts =~ /\d+/g;
        my @exon_ends   = $exon_ends   =~ /\d+/g;

        die "Data discrepancy" unless @exon_starts == $n and @exon_ends == $n;

        my $introns = $n - 1;    #amount of introns = exons - 1
        $total_introns += $introns;

        my $sequence = $chromosome{$chr} or die "No such chromosome";

        for my $i ( 0 .. $introns-1 ) {

            my ($intron_start, $intron_end) = ( $exon_ends[$i], $exon_starts[$i+1] );

            my $intron_prefix = substr( $sequence, $intron_start, 2 );
            my $intron_suffix = substr( $sequence, $intron_end-2, 2 );

            if ( $sense eq '+' ) {
                ++$GUAG_introns if $intron_prefix eq 'GT' and $intron_suffix eq 'AG';
            }
            elsif ( $sense eq '-' ) {
                ++$GUAG_introns if $intron_prefix eq 'CT' and $intron_suffix eq 'AC';
            }
        }
    }
}

printf "Number of GUAG introns = %d\n", $GUAG_introns;
printf "Total introns = %d\n",          $total_introns;
printf "%.1f%% of GT-AG introns.\n\n",  $GUAG_introns / $total_introns * 100;

output

Processing HG38:
    chr1
    chr10
    chr11
    chr11_KI270721v1_random
    chr12
    chr13
    chr14
    ...

Number of GUAG introns = 492784
Total introns = 499504
98.7% of GT-AG introns.

[Finished in 39.1s]


Project Euler Problem 21 in Python: Summing amicable numbers

In your sum_div method, 1 is always a divisor, and n/1 is never a “proper” divisor of n.  So you can remove the “1” case from your loop, and get rid of the x != 1 test, for a slight speed increase.

Also, if n % x == 0, then the other divisor is n // x; no call to int() is required.

Finally, no list creation is required.  Just maintain a running total.

def sum_div(n):
    total = 1
    for x in range(2, int(math.sqrt(n) + 1)):
        if n % x == 0:
            total += x
            y = n // x
            if y > x:
                total += y
    return total

In your main loop, your search for i,j both in range(1,10000), and add both i, j (if different) to your set to ensure you don’t have duplicates.

You can cut down your search space by half by recognizing that if you find one pair i, j, you have also found the other pair j, i, and adding the other pair to the set is a no-op.  You only need to search the cases where (say) i < j is true, which eliminates just over half of the pairs.

for i in range(1, 10000):
    for j in range(i+1, 10000):
        if sum_div(i) == j and sum_div(j) == i:
            amicable_nums.update([i, j])

How many times are you computing sum_div(i)???  Does it change in the inner loop?  Maybe you could only compute it once per loop?

for i in range(1, 10000):
    sdi = sum_div(i)
    for j in range(i+1, 10000):
        if sdi == j and sum_div(j) == i:
            amicable_nums.update([i, j])

Do you really need the inner loop?  sdi == j will only be true for exactly one value in the loop.


A few general things first:

' is the conjugate transpose, not the transpose. These are the same for real values, but will behave differently when you have complex values. To avoid confusion, it is recommended that you always use .' when transposing a matrix, even if it's real.

You're using both disp('text') and disp('[text]'). The first one works for plain strings, while the other must be used when concatenating strings and numbers. I suggest you either use brackets on all calls to disp, or skip the brackets for all calls to disp where the string is plain text. Consistency is always nice.

Variable names:

The variable names are well chosen and descriptive. One minor comment is that you're using correct_size and correct_board, but blocks_ok. correct_blocks is probably a better word here, to keep consistency.

Frequently used variables:

There are a few variables that are used over and over again. You should declare the following variables outside the loop:

sq_rows = sqrt(rows);
values= 1:rows;

Avoid the loop and calls to unique by sorting the board by rows and columns:

You can avoid the loops by sorting all columns of the regular board, and the board when it's transposed, instead of checking for unique values.

isequal(sort(board), sort(board.'), repmat(values.',1, rows))

repmat(values.',1,rows) produces a matrix looking like this:

1     1     1     1
2     2     2     2
3     3     3     3
4     4     4     4

Alternatives to repmat(sqrt(rows),sqrt(rows),1):

Using mat2cell to create cell_blocks is good, but the expression can be simplifed using the new pre-defined variables. There are some alternatives to repmat(sqrt(rows),sqrt(rows),1) that are more readable, such as:

ones(sq_rows,1) * sq_rows;
zeros(sq_rows,1) + sq_rows;

repelem is an option if you're using MATLAB version R2015a or newer.

Use cellfun when you're working with cells, and arrayfun when you are working with other "stuff".

Since cell_blocks is a cell array, you can use cellfun:

all(cellfun(@(x) isequal(unique(x),values.'), cell_blocks))

Simplifying the disp-calls:

You know that the first number in the sequence is 1, so you can simplify the two disp-calls in the middle:

disp(['Numbers 1-' num2str(rows) ' are present in all rows and columns'])

I believe you're missing a break after checking the size of the board (first if).

Comments!

I suggest you use a lot more comments! Explain what the different parts of your code do.


In your code, the variable result is just of type object because the compiler doesn't know what the result of FirstOrDefault is going to be.

Below I've used explicit typing using T for clarity and so that var doesn't evaluate to object

I created this extension method so that you wouldn't have to cast the object everytime you wanted to use it... this takes care of that before it returns

public static class ExtensionMethods
{
    public static T FirstOrDefault<T>(this ExpandoObject eo, string key)
    {
        object r = eo.FirstOrDefault(x => x.Key == key).Value;
        return (r is T) ? (T)r : default(T);
    }
}

What follows is a re-implementation of the original post's code using the above method

ExpandoObject model = GetExpandoObject();

var someExpandoObject = model.FirstOrDefault<ExpandoObject>("node");
if (someExpandoObject == null) return;

var kvp = someExpandoObject.FirstOrDefault<KeyValuePair<string, object>>("children");
if (kvp.Equals(default(KeyValuePair<string, object>))) return;

var ilo = kvp.Value as IList<object>;
if (ilo == null) return;

someExpandoObject = ilo.FirstOrDefault() as ExpandoObject;
if (someExpandoObject == null) return;

someExpandoObject = someExpandoObject.FirstOrDefault<ExpandoObject>("node");
if (someExpandoObject == null) return;

object finalResult = someExpandoObject.FirstOrDefault<object>("stuff");

What follows is another possible implementation using nested if statements instead of multiple return statements.

ExpandoObject model = GetExpandoObject();

ExpandoObject someExpandoObject;
KeyValuePair<string, object> kvp;
IList<object> ilo;
object finalResult;

if ((someExpandoObject = model.FirstOrDefault<ExpandoObject>("node")) != null)
{
    if (!(kvp = someExpandoObject.FirstOrDefault<KeyValuePair<string, object>>("children")).Equals(default(KeyValuePair<string, object>)))
    {
        if ((ilo = kvp.Value as IList<object>) != null)
        {
            if ((someExpandoObject = ilo.FirstOrDefault() as ExpandoObject) != null)
            {
                if ((someExpandoObject = someExpandoObject.FirstOrDefault<ExpandoObject>("node")) != null)
                    finalResult = someExpandoObject.FirstOrDefault<object>("stuff");
            }
        }
    }
}

Update:
Using a newer feature of C# null-propagation, we can string all these calls together. Now we no longer need to save each object down the chain (unless we want to).

Here is an implementation using null-propagation.

object finalResult = ((model.FirstOrDefault<ExpandoObject>("node")
    ?.FirstOrDefault<KeyValuePair<string, object>>("children").Value as IList<object>)
    ?.FirstOrDefault() as ExpandoObject)
    ?.FirstOrDefault<object>("stuff");


This seems quite fine. It's good that you are using prepared statements for all database queries.

What bugs me the most is that the users table is reused for multiple purposes:

Store essential user information such as email and password
Store information about tracking reset password requests

It would be better to use another table for the 2nd purpose.
The reason is that the users table is an essential piece of your site and you wouldn't want anything to happen to it by accident.
So the less you touch that table, the better.
Besides, for most users the new_password_key and new_password_requested fields will be blank / unused most of the time.

The variable names are sometimes not so great. For example:

$value = isset($_GET['key']) ? $_GET['key'] : null;

$value is a key, so I suggest to name it accordingly.

One last small thing, I recommend to use braces with all if, else if statements.


Catch invalid input
When I was trying out your code, I entered Cntrl + Z which crashed the program. Using Try and Except can prevent this from happening
try:
    word = input("Enter your word:")
except Exception:
    print("Invalid input!")

Also, I'd keep a check of len(word) == 0 since an empty input is dangerous too

Reading grid.txt
with open('grid.txt', 'r') as f:
    lst = [[a for a in l.strip() if a != ' ' and a!= '\n'] for l in f.readlines() if l]
    lst2 = [a[::-1] for a in zip(*lst)]

You can greatly simplify this part by using list.split()
with open('grid.txt', 'r') as f:
    lst = [line.split() for line in f.readlines()]
    lst2 = list( zip (*lst[::-1]) )

If you're worried about the '\n' at the end, the new lists using this method will not have it.

I'd suggest you keep the names of the lists as horizontal and vertical rather than lst and lst2 which don't mean much

Split work into functions
You should separate tasks into functions so that there isn't one huge block of code that does everything. Moreover, splitting work into functions makes it easy to maintain your code. What if your main game loop could look like this
def game_loop():
    while True:
        word = take_input()
        matches = find_matches(grid,word)

        if matches == None: print("No matches")
        else:
            for match in matches:
                print( "Match: " + match )

        if input("Do you want to play again? (y/n): ").lower() == 'n':
            break

An alternate approach
The reason your code isn't as efficient as the method I will just show you is that you repeatedly reverse the lists and use a lot of loops. There is a much better and cleaner way in which you need to go through the whole grid only once.

Read the .txt file into a list ( like we previously did for lst)
Start by going through each element in the 2-D list
If the element matches the first character of the entered word, check all 8 directions to complete the match

Implementaion


I was thinking of maybe having a constructor for each profession that used true or false to denote if it was a good saving throw or bad one. That's just really bad though, I think, since it doesn't give any information when reading it.

I suppose you mean that this would not be particularly readable:

enum ProfessionType {
    BARBARIAN(false, true, false),
    BARD(true, false, true),
    WIZARD(true, false, false);
    // ...
}

Instead of booleans, you could use enums, like Will.STRONG, Fortitude.WEAK, and so on.
The result will be more readable and less boilerplate.

With this refactoring,
the methods like getWillModifier will be no longer abstract,
and would contain the logic (probably a switch) to get the right value given the property of the enum, and the level.

In general, enums are not so well-suited to have behaviors (custom methods),
they are much better as plain values,
possibly with some common behavior (non-abstract methods).

Another alternative world be to use the builder pattern to build attributes, with a syntax like this:

BARBARIAN(Attributes.builder().will(WEAK).fortitude(STRONG).build()),

Where WEAK and STRONG could come from a Defense enum.

That said, the other answer makes an excellent point that perhaps the attributes should not be hardcoded, but read from a configuration file. You would gain a lot of flexibility, such as adding new types or changing the attributes without recompiling the code.


Creating an array of random numbers with no duplicates

No, not a good way at all.

shuffle and containsDuplicate recursively call each other without guarantee to ever stop doing that. That is the program has a certain probability to die because of stack overflow.

A similar non-recursive version

    public static boolean containsDuplicates(int[] arr) {
        return arr[0] == arr[1] || arr[0] == arr[2] || arr[1] == arr[2];
    }

    public static void shuffle(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            arr[i] = genRandom();
        }
    }

    public static void main(String[] args) {
        do {
            shuffle();
        } while(containsDuplicates());
    }

doesn't suffer stack overflow, but still may run for indefinitely long time.

As Jerry Coffin mentioned in the comment, a Fisher-Yates algorithm is a way to go.


This one line might be left as-is, it's short and simple enough to be fully understood at first sight (especially if outer method has a meaningful name). However it has the disadvantage to be hard to test because it is doing 3 things:

Getting the assembly which is the entry point of your application.
Resolving the full path of that assembly.
Reading the version information of that assembly.

In an ideal world I'd probably want to test them in isolation but it might happen only when I will have a bug there, for sure I want to reuse this code elsewhere then I will introduce separate methods.

public static FileVersionInfo GetProductVersion()
    => FileVersionInfo.GetVersionInfo(GetEntryAssemblyPath()).ProductVersion;

public static string GetEntryAssemblyPath()
    => GetAssemblyPath(Assembly.GetEntryAssembly());

I changed typeof(Program).Assembly to Assembly.GetEntryAssembly() because if I move it into a separate DLL then I won't have Program. Note, however, that they may differ (see later).

What I'd really change is the way you obtain the path. Hard-coding file:// is tricky and unnecessary and you do not handle URL escapes. Moreover it will return an incorrect result if assembly has been loaded with Load(). It's easier to write a slightly more correct version:

public static string GetAssemblyPath(Assembly assembly)
     => Uri.UnescapeDataString(new UriBuilder(assembly.Location).Path);

Note that here I'm accessing Assembly.Location but it throws an exception for dynamically generated assembly and it's an empty string for assemblies loaded with Load(). A "better" version should then handle both cases:

public static string GetAssemblyPath(Assembly assembly)
{
    if (assembly.IsDynamic || assembly.Location == String.Empty)
        return ""

     return Uri.UnescapeDataString(new UriBuilder(assembly.Location).Path);
}

Little bit better but if we want to make GetEntryAssemblyPath() a reusable method we should do better because the entry assembly is not always defined (web applications come to my mind in this moment but I kind-of remember about other issues in hosted environments). The choice between Assembly.CodeBase and Assembly.Location isn't important here but in another context you should check for Assembly.Location == String.Empty also when using Assembly.CodeBase.

In your tests you can now verify GetAssemblyPath() in isolation and you may add separate tests for other functions when you will find an issue there (or when their code will be more complicate).

Last pedantic note: we're not checking if file effectively contains the required information and, usually, for assemblies it's also possible to read ProductInformationalVersionAttribute (which might be different).


The implementation of sundaram's sieve that you've mentioned returns primes in sorted order. So, sorted() is not needed.

Also, it is best to define prime_list = primes() outside the definition of prime_factors_generate (This will reduce calls to primes()). You can argue that that will make the code less functional but that would be nitpicking [Even the definition of primes() isn't functional]

EDIT: As pointed out in a comment by mteckert, my earlier solution will not provide the desired result. This EDIT will work though (It'll return [2, 2, 2, 3] instead of [2, 3] for prime_factors_generate(24))

def max_pow(n, x):
    if n%x == 0:
        return max_pow(n/x, x)+1
    else:
        return 0

def prime_factors_generate(n): #Variables added just for convenience. Can be removed.
    prime_list = primes()
    nested_ans = map(lambda x: [x]*max_pow(n, x), prime_list)
    ans = [item for sublist in nested_ans for item in sublist]
    return ans

One liners (if you're interested in them) for max_pow and prime_factors generator:

max_pow = lambda n, x: max_pow(n/x, x)+1 if n%x==0 else 0
prime_factors_generate = lambda n: [item for sublist in map(lambda x: [x]*max_pow(n, x), primes()) for item in sublist]

End of EDIT. I'm leaving my earlier solution intact (which returns [2, 3] for prime_factors_generate(24)).

This should work:

def prime_factors_generate(n): #Variables added just for convenience. Can be removed.
    prime_list = primes()
    prime_factors = filter(lambda x: n % x == 0, prime_list)
    return prime_factors

Or if you're into one liners:

prime_factors_generate = lambda n: filter(lambda x: n % x == 0, primes())


So, a few notes:

Your filtering is too broad. If you had other elements in the DOM with class phase, they would also be filtered, even though they aren't part of the list. Instead, it's better to limit what you're selecting -- DOM elements have querySelectorAll, getElementsBy..., etc., to ensure that you're limiting the results to that element's children.
This can't be re-used very well -- make it more modular. You can do this by passing in the ID of the search field and the list (and any additional selectors).
I'd suggest using classes to toggle visibility, because at some point you might actually want the styling to be different. Note that classList is only available on modern browsers (http://caniuse.com/#feat=classlist).
Cache your lengths when iterating over an Array-like.
There's no need for parentNode if you use textContent. Then you can query for all lis in the list and filter them instead. This also means you don't have to add classes for each list item unless you want to. In my example, I've removed the class='phase' portion of your anchors.
I assume your items are eventually going to be links to elsewhere, so I left the anchors in the example.

var liveFilter = (function() {
  /**
   * Initializes a search field with associated list and filters it live while typing
   *
   * @param {string} searchFieldId     An ID of a search field input element
   * @param {string} listId            An ID of an element containing items that should be filtered
   * @param {object} [options]         Specifies additional options:
   *                                   * selector: specifies a query to be run against list; the results
   *                                     will be filtered according to the value of the search field. If
   *                                     not specified, the filter matches all direct children.
   *                                   * filterClass: specifies a class name to be applied to items that
   *                                     are going to be filtered out. If not specified, defaults to
   *                                     "filter-hidden".
   */
  function liveFilter( searchFieldId, listId, options) {

    var searchField = document.getElementById(searchFieldId),
        list = document.getElementById(listId),
        selector,
        filterClass;

    if (!searchField) {
      throw new Error("No search element found with id " + searchFieldId);
    }

    if (!list) {
      throw new Error("No list element found with id " + listId);
    }

    if (options !== undefined) {
      selector = options.selector;
      filterClass = options.filterClass;
    }

    if (filterClass === undefined) {
      filterClass = "filter-hidden";
    }

    var handler = function searchFieldChanged() {
      var text = this.value,     // this will be bound to the search field
          regexp = RegExp(text, 'i'),
          nodes = (selector === undefined) ? list.children
                                           : list.querySelectorAll(selector),
          node;
      for (var i = 0, l = nodes.length; i < l; i++) {
        node = nodes[i];
        if (node.textContent.search(regexp) < 0) {
          // note: classList is only available on modern browsers
          node.classList.add(filterClass);
        } else {
          node.classList.remove(filterClass);
        }
      }
    };

    // input is for modern browsers
    searchField.addEventListener("input", handler, false);
  }

  // If using CommonJS, you'd do module.exports = liveFilter, and it could be required later.
  return liveFilter;
})();

liveFilter("filter", "list", { selector: "li", filterClass: "filter-hidden" });
.filter-hidden {
  display: none;
}
<input type="text" id="filter" />

Ruby on Rails

The Rails Way

Pickaxe Guide

jQuery HTML

CSS HTML AJAX

HTML5 Net Set

Node Easy

Listing Bloop


In no particular order:

Your code needs more documentation.

There are no comments or docs to help me understand how the code works, or why it was written the way it was. If I don’t know why the code was written this way, I can’t tell whether it’s working correctly – this makes it harder to review, edit and maintain.

There’s Python PEP 257, which describes how you should document a function with docstrings. (PEP means “Python Enhancement Proposal”, like a public design doc for Python.)

As a side note, when I read make_list(), I assumed that it took a single line (one string), which was a little confusing.  It wasn't until I saw it called later on that I realised it took an iterable of strings – a collection of lines.  Beware confusing typos like this.
Prefer comprehensions to loops and lambdas.

Python has a feature called comprehensions, which is a very powerful way for quickly constructing lists, sets and dictionaries. If you’re unfamiliar with the concept, I quite like this introduction.  This is often considered to be one of the highlight features of Python.

This lets you write for loops in a more succinct way, for example in get_numbers():

def get_numbers(lists):
    return [x[1] for x in lists]

If the for loop is simple, these are generally considered more Pythonic.

Lambdas are considered fairly un-Pythonic, especially when comprehensions are available. For example, I'd rewrite line 10 as:

lines = [line.strip() for line in lines if line.strip()

Use with open() rather than open() … close().

The preferred approach for opening files is as follows:

with open(pride_and_prejudice_path, 'r') as infile:
    # do stuff with infile

This construction ensures that the file is always closed correctly – if you make explicit calls to open() and close(), something could go wrong in the middle and you might not close the file correctly.

Note also that you can iterate over the contents of the file directly, rather than calling readlines() first:

with open(pride_and_prejudice_path, 'r') as infile:
    lines = [name.strip() for name in infile if name.strip()]

Note that calling readlines() will store every line in a list, before you can do anything – depending on the size of the file you’re looking at, this can be prohibitively large.  Often better to skip readlines() and iterate over the file directly.
Try to avoid unnecessary imports.

The only import you’re actually using is operator.itemgetter(). It’s good practice to avoid importing things that you don’t use.

In the same vein, don’t create variables you don’t need, e.g. the counter variable in count_words().
Read PEP 8, the Python style guide.

In general, your code is pretty good. A few small things I noticed:

On line 41, you seem to have over-indented by 4 spaces.
On line 42, you shouldn’t have spaces around the = sign in keyword arguments, i.e.,

return sorted(word_count, key=itemgetter(1), reverse=True)

Line 56 should be broken up for readability, probably by assigning new_list[counted_words.index(x)] to a constant. (Regardless of the line length in the standard, it’s just unwieldy.)

Use __future__.division instead of casting to floats.

I can see that you’re casting to float in quite a few places, because Python 2.7 defaults to integer division. Python 3 behaves in a more sensible manner (and I’d recommend using Py3 if you’re starting from scratch). To get this behaviour in the older versions of Python, you can add

from __future__ import division

to the top of your code. This will let you clean up your float() calls.

Note that __future__ imports must precede any other imports.
Use data structures other than lists.

In count_words(), you're using a list of lists to keep track of how many times a word appears in the text.  A better data structure would be a dictionary.

Further, you're constructing multiple intermediate lists to get this structure.  All of those consume memory and take time to construct.  If you move this up to where we iterate over the file, we can skip those lists and go much faster:

word_counter = dict()
with open('prideandprejudice.txt', 'r') as infile:
    for line in infile:
        if not line.strip():
            continue
        for word in cleanup(line):
            if word in word_counter:
                word_counter[word] += 1
            else:
                word_counter[word] = 1
counted_words = sorted(word_counter.items(),
                       key=itemgetter(1),
                       reverse=True)

On my machine, your original code took ~40s to run.  My updated version runs in <1s.  Those intermediate lists had a big performance impact.

Note that you could use collections.defaultdict to tidy that code up even further.
Use enumerate() for a more Pythonic loop.

Your cleanup() function has a classic pattern for people coming to Python from other languages:

i = 0
while i < len(iterable):
    item = iterable[i]
    # do stuff with item
    i += 1

Python has loop constructions that make this much nicer.  In cleanup(), you can use enumerate to iterate over the index and the character together.  This is more explicit, and makes for cleaner code.  Like so:

for idx, char in enumerate(text):
    if char in punct:
        continue
    elif char in (" ", "-"):
        new_text.append(" ")
    else:
        new_text.append(char.lower())

Use collections.namedtuple to clean up the output of check_zipf.

Using namedtuples is a very easy way to improve the readability of code, by assigning named attributes to items.  Reading the output of your check_zipf() function, all I get is lists of numbers.  What do these numbers mean?  Their indices mean nothing to me (especially as you haven't included comments).

Namedtuples, and good attribute/variable names, can make it much easier to see what's going on.  For example:

Word = collections.namedtuple('Word', 'observed expected chi_square')

def check_zipf(counted_words):
    zipfed_words = {}
    baseline_observed = counted_words[0][1]
    for idx, (word, observed) in enumerate(counted_words):
        expected = baseline_observed / (idx + 1)
        chi_square = ((observed - expected) ** 2) / expected
        zipfed_words[word] = Word(observed, expected, chi_square)
    return zipfed_words


Validation of Identification card fields (string and array)

Your code looks good, but I notice that you are a Portuguese speaker (as I am), so my only advice would be: Code in English.

There is a good article about idioms and programming called "Why you shouldn’t code in Spanish". In the article the author even uses PHP in the scripts as examples.

Like the old saying:

  "Always code as if the person who ends up maintaining your code is a
  violent psychopath who knows where you live."

We should code our code in a way that the majority of programmers will understand, so in a way we should (almost always) code in english.


jQuery security and efficiency simple calculation code

Security:

If you want to check amounts securely, don't do it in the browser alone: you need a server-side validation (e.g. with PHP if it is your language of choice).

Efficiency:

You can use $('...') instead of jQuery('...') to improve the readability and concision (source: jquery.com).
Avoid looking for divs with jQuery every time you need them by assigning them to a variable. In this case, caching $('#total-amount') seems unnecessary, but it will pay off as soon as you call it once more (see jQuery Best Practices for more information).

Thus:

//AMOUNT CALCULATOR
var totalAmount = serviceAmount = 0;
// caching $('#total-amount')
var totalAmountDiv = $('#total-amount');

$('.select-service').click(function(){
    // caching $(this)
    var thisDiv = $(this);
    var serviceAmount = parseInt(thisDiv.parent().html().replace(/\D/g,''));
    if(thisDiv.is('.selected')){
        thisDiv.removeClass('selected');
        totalAmount -= serviceAmount;
        totalAmountDiv.html(totalAmount);
    }else{
        thisDiv.addClass('selected');
        totalAmount += serviceAmount;
        totalAmountDiv.fadeIn('slow').html(totalAmount);
    }
});
//AMOUNT CALCULATOR


Another Sliding Window - find each `k-size` window the maximum num. from an integer array/list

I don't see any obvious improvements to your algorithm.
Tests:
Your "main" section seems to be checking if the algorithm works, but you can make better use of the examples provided with the original prompt.
Constraints:
The original prompt makes certain promises about the inputs. It's reasonable to just take those as assumptions, or (maybe better, depending on stuff) to make them explicit assertions, but there's no need to handle violating cases.
Typing:
You've got type-hints in your function signature.
That's great!
But in python the idea of "types are comments that can't be wrong" only holds if you actually use a type-checker. Trying mypy on your code gives an error that it can't figure out the type of q. The easiest fix for this would be to use the Deque from typing (or upgrade to python 3.9) so you can write q = Deque[int]().
Begging for microseconds:
You can save yourself some conditional checks by changing how you handle the first couple rounds: Start the loop with something in the deque, and slice off the head of the result-list at the end. On the other hand, trying to optimize at that level of granularity is easy to get wrong. I banged out an over-engineered version, but without benchmarking this is worthless.
from typing import List, Deque, Iterable, Tuple, Callable
from itertools import islice

def _window_func(k: int, q: Deque[Tuple[int, int]]) -> Callable[[Tuple[int, int]], int]:
    def retval(pair):
        if q[0][0] == pair[0] - k:
            q.popleft()
        while q and q[-1][1] < pair[1]:
            q.pop()
        q.append(pair)
        return q[0][1]
    return retval

def maxSliding(nums: List[int], k: int) -> List[int]:
    assert nums
    assert 1 <= k <= len(nums)
    return list(islice(
        map(_window_func(k, Deque([(-1, nums[-1])])),
            enumerate(nums)),
        k - 1, None
    ))

tests = [([99,74,48,27,56,88,66,77,101], 3, [99,74,56,88,88,88,101]),
         ([1,3,-1,-3,5,3,6,7], 3, [3,3,5,5,6,7]),
         ([1], 1, [1]),
         ([1,-1], 1, [1,-1]),
         ([9,11], 2, [11]),
         ([4,-2], 2, [4])]

if __name__ == '__main__':
    for (l, k, result) in tests:
        try:
            actual = maxSliding(l, k)
            assert actual == result
        except:
            print(f'Offending test {(l, k, result)}, got {actual}')
            raise
    print("tests passed")
```


Possibly the most egregiously non-Scala thing in your code is the if...else if...else if...else chain.  Those are a bad smell in any language, particularly OO ones or functional languages with pattern matching.  Scala is both.  That really has to go.

Folding is the most efficient and functional way to solve this, but that's a more advanced subject for somebody who is new to Scala and FP.  Here is a simple recursive solution which illustrates the clarity of pattern matching:

def balance(chars: List[Char]): Boolean = {
    def go(cs: List[Char], level: Int): Boolean = cs match {
        case Nil => level == 0
        case ')' :: _ if level < 1 => false
        case ')' :: xs => go(xs, level - 1)
        case '(' :: xs => go(xs, level + 1)
        case _ :: xs => go(xs, level)
    }
    go(chars, 0)
}

This should show how much pattern matching simplifies a recursive procedure.  Each match defines one of the possible states and the appropriate action.

Because I used pattern matching in this way

It is clear that I have comprehensively covered the possible range of states (OK, I haven't dealt with Null but this is Scala - don't use Null).
The corresponding actions are simple and the small differences between each one easy to see.

Compare this with the complexity, lack of clarity and fragility of your if...else if chain.  It is hard to compare your different conditions, hard to see if you have been comprehensive and nothing about an if chain even compels you to be testing related conditions - you can have anything in each condition.

This is a naive example but it is a good place to start.  That said, Ben's is the best answer.

There is a very small amount of code duplication in this version.  The final three pattern matches do the same thing with only a minor change to the input parameters.  In such a small, easy to read set of code this is really not a sin (and addressing that would make the function structure more complex and less clear). Replacing the recursion with a fold, however, would remove the duplication, because the fold would take care of the repeated application of the function,which could be reduced to a simple closure adjusting the level.

Other notes about this solution:

It is fully tail recursive optimisable, unlike your code (again, the pattern matching makes this easy to see, where the if chain does not)
Adding a @tailrec annotation is good practice in such Scala code
It uses an inner function for recursion rather than exposing internal state (unlike your accepted answer).


Class made to do some basic RGB analysis

All those inner functions in your constructor are unnecessary. Inner functions should be used sparingly, normally you have only these cases:

Functions which can do something based on parameters you pass to it and which are not directly related to some object. Make these functions stand-alone functions.
Functions which do something with an object or return some information about that object. Make these functions methods (or properties) of the class of the object.
Functions which logically belong to some class because they make only sense in combination with them. Make these functions static methods of the class (by adding the decorator @staticmethod).

In your case I would do Option 2 (with the addition of making them properties which will be calculated when you first access them).

class Img:
    def __init__(self,filename):
        self.name = filename
        self.image = Image.open(self.name) # open image using PIL

        # convert the image to a pandas df
        self.df = pd.DataFrame(data=list(self.image.getdata()))

        # get the RGB values from the image
        self.r = self.df[0].mean()
        self.g = self.df[1].mean()
        self.b = self.df[2].mean()

        self._luminance = None
        self._contrast = None

    @property
    def luminance(self):
       """Calculate luminance (brightness) based on the RGB values"""
        if self._luminance is None:
            self._luminance = (0.299*self.r + 0.587*self.g + 0.114*self.b)
        return self._luminance

    @property
    def contrast(self):
        """Calculate the contrast using the Michelson contrast formula."""
        if self._contrast is None:
            min_ = self.luminance.quantile(0.05)
            max_ = self.luminance.quantile(0.95)
            self._contrast = (max_ - min_) / (max_ + min_)
        return self._contrast


Defect per line of code.

Code defects AKA bugs have a strong correlation to the number of lines of code (*1). Across all languages, coding styles, and domains there is a consistent defect rate. The industry average is about 20 per 1000 lines of code.

The metric is simple.

  "... a count of lines in the text of the program's source code excluding comment lines." (*2)

One of the simplest ways to reduce defects is to reduce the number of lines. This dose not mean putting everything in one line is a good idea, nor does it mean that sprawling out what would be a single line, to many lines, does not add to the line count.

Reducing your code

So with that in mind your code is a little low density, meaning that there are more lines than are needed to do what you want done.

Reducing your code while still using the same logic yields the following

const path = 'rootFolder/folder1/exampleFolder1/folder3/folder3/subFolder123/file2.md';

const info = path.split('/').map((name, index, dirs) => {
    const item = {name};
    if (index < dirs.length - 1) {
        item.url = '';
        for (let i = 0; i <= index; i++) {
            item.url += `/${dirs[i]}`;
        }
    }
    return item;
});

console.log(info);

Ignoring the top and bottom lines we now have 10 lines.

This is still a little long as the inner loop is just a Array.join but limited to the current index.

If we look for ways to reduce the size we can see that the need to exclude the URL from the file name is adding complexity. Unless there is a good reason to not have the URL we can just treat all items equally.

const path = 'rootFolder/folder1/exampleFolder1/folder3/folder3/subFolder123/file2.md';

const dirs = path.split('/');
const info = [];
while (dirs.length) {
    info.unshift({ url : "/" + dirs.join("/"), name : dirs.pop() });
}

console.log(info);

We are now down to 5 lines. And personally info can share the declaration with dirs

const path = 'rootFolder/folder1/exampleFolder1/folder3/folder3/subFolder123/file2.md';

const info = [], dirs = path.split('/');
while (dirs.length) {
    info.unshift({ url : "/" + dirs.join("/"), name : dirs.pop() });
}

console.log(info);

We have reduced the number of lines from 12 to 4, reducing the chance of defect by over half.

- (*1) Steve McConnell, Code Complete

- (*2) wiki, Source lines of code


Pythonic way of managing data for plotting 2D variance plots

Your function proc can be greatly reduced by using the fact that numpy functions are vectorized and most of them take the axis to act upon as an argument. This is certainly true for numpy.median and numpy.percentile.

import numpy as np

def proc(data):
    return (np.median(data, axis=0),
            np.percentile(data, 25, axis=0),
            np.percentile(data, 75, axis=0))

You can also use a for loop for plotting, to avoid duplicating everything:

if __name__ == "__main__":
    colors = '#B22400', '#006BB2'
    file_names = 'subject_1', 'subject_2'

    for file_name, color in zip(file_names, colors):
        subject = load('/Desktop/', file_name)
        med, perc_25, perc_75 = proc(subject)

        # lets plot only x (second column)
        med = med[:, 1]
        perc_25 = perc_25[:, 1]
        perc_75 = perc_75[:, 1]

        fill_between(x, perc_25, perc_75, alpha=0.25, linewidth=0, color=color)
        plot(x, med, linewidth=2, color=color)

Note that x is currently undefined (as in your code).

I also added a if __name__ == "__main__": guard to allow importing from this script without executing the plotting.

In addition I changed your indentation to conform to Python's official style-guide, PEP8:

This

med     = med[:, 1]
perc_25 = perc_25[:, 1]
perc_75 = perc_75[:, 1]

should just be

med = med[:, 1]
perc_25 = perc_25[:, 1]
perc_75 = perc_75[:, 1]

as noted under Pet Peeves (of Guido van Rossum, the creator and BDFL of Python).


NULL-eating / elimination version of fgets() in C

There's absolutely no need for an intermediate (dynamic) buffer. Everything you do can be done directly in the client buffer (Buf).

I don't see a reason for fread-ing data. fgets works as good, and spares you from calling ftell and fseek.

The way you remove null chars is suboptimal. I'd keep count of null chars encountered, and shift non-null chars by that count, in a single loop. In any case, I'd factor removal code into a separate function (No Raw Loops rule strikes again).

Looking for a newline is better be done with a standard memchr().

That said, the main code condenses to

char * fgets_and_remove_nulls(char * buf, size_t count, FILE * fp)
{
    memset(buf, 0, size);
    if(fgets(buf, size, fp) == NULL) return NULL;
    char * end = memchr(buf, '\n', size);
    if (end == NULL) end = buf + size;
    remove_null_chars(buf, end);
    return buf;
}


Please critique my Enumerable DataReader with yield and log data access pattern

Initially, I shared your concern over resource disposal.  My assumption was that there was the possibility the command could be left hanging around in cases where you did not enumerate over the entire collection (as with something like FirstOrDefault).

However, a few quick tests with a test project reveals that the using statement performs its clean-up as soon as you are done with the enumerator.  A LINQ statement or a foreach loop may only partially traverse the results, but they both still clean up the enumerator when exiting scope.

Keep in mind, though, that there is still potential confusion that might arise from the deferred execution of GetSomeData.  The command doesn't execute until you start enumerating the result.  If anything were to modify the data before between the time you call GetSomeData and when you enumerate the result, you could get different results than you expect.


If you're going to use flex, use flex! Flex inherently helps with margin control.

Margins are great, but you're essentially saying, I want to learn flex, except when it's easier/convenient to go back to what I've been doing.

Some key topics of interest regarding your concerns:

  To maintain a good page structure for SEO...

Great! That's a good attitude to have. You should always follow the W3C specs for best practices of what content goes where. If you don't like reading long-winded documentation.. MDN always has a great synopsis of elements/attributes/rules/principals/best practices (usually in a blue box).

Buttttt having a header inside  tags isn't necessarily against standards, in fact, all flow content is permitted. ref

Additionally, in your circumstance, it acts as a main content link, so I would argue it belongs there.

However, keeping in mind the importance of a semantic elements purpose is a very good outlook imo.

Furthermore on this point, I can not tell you how many developers overlook accessibility. Not only does it help you with SEO, it absolutely is critical to how disabled persons rely on their devices. It often takes trivial amount of time to make a website accessible friendly, but developers generally don't consider it because either they themselves aren't disabled and it's in the back of their mind, they haven't had any complaints, they don't work for someone who cares to implement it. But that is beyond the scope of the question, either way you are on the right track with that mentality.

  I've recently migrated away from floats and have started using flexbox

Not a bad thing, will definitely make it easier for you, but try not to consider them synonyms. Float properties apply to all elements, even flex, but flex properties do not apply to all elements. With the following caveats:

float applies but no effect is taken if display = none
float applies but no effect is taken if element is flex

An example of why they are not synonymous is float:left for an  tag around text will allow that text to flow around the content, whereas flexbox is ... well a box and the text will maintain in it's rect bounds instead of wrapping around the box next to it.

An important thing to embrace with flex is that as soon as you set an element to display: flex the direct children of that container become flex items. So note the hierarchy there.

Take this example where 'C' is not a direct descendant of .wrapper, therefor it doesn't inherit properties.

.wrapper {
  display: flex;
  flex-flow: column nowrap;

  height: 175px; padding: 10px; border-color: red;
}

.b, .c {
   float: right;
   border-color: green;
}
.c {
  background-color: lightgrey;
}

/** irrelevant **/
div {
  height: 50px;
  border: 1px solid;
}
.a { border-color: blue; }

:::::: A :::::::

:::::: B ::::::

:::::: C ::::::

I bring that up, because navigation items are generally top-level children, so we can consider that in circumstances like margin-top: -24px. You can take the following snippet (unchanged from OP, other than color for effect) and see why it can be problematic real fast, and worse, it can easily create a domino effect where you will have to add margins to a lot of other things just to create synergy:

/*------------------------
Default grid
-------------------------*/

.flex {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}

.col {
  flex: 1;
}

/*------------------------
Columns
-------------------------*/

.has-2-columns .col {
  flex: none;
}

.has-2-columns .col {
  width: 49%;
}

/*------------------------
Logo
-------------------------*/

.site-title {
  position: relative;
  /* Enables z-index */
  z-index: 1;
  /* Positions logo above .main-navigation */
  width: 80px;
  margin: 0 auto;
  background: #ccc;
}

/*------------------------
Main navigation
-------------------------*/

.main-navigation {
  position: relative;
  margin-top: -24px;
  /* Brings nav inline with .site-branding */
  z-index: 0;
  /* Ensures nav is below .site-branding */
}

.main-navigation ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.main-navigation ul li {
  display: inline-block;
}

.left-menu {
  text-align: left;
}

.left-menu li {
  margin-right: 24px;
}

.right-menu {
  text-align: right;
}

.right-menu li {
  margin-left: 24px;
}

.site-header {
  background: pink;
}

Demo

Home

About

Contact

Store

So that is why I say, if you're going to use flex, then use flex! Take advantage of it. Let it do all this work and calculations for you. Additionally, I don't know if you have begun plans for this or not, but this isn't really responsive friendly as it stands now.

TLDR;

Revisiting requirements

  My navigation has 4 menu items. I'd like my logo to sit in the middle of these

The way you have set it up, as you can see get's the job done. But they are not apart of the same parent, therefor they can't take advantage of it's inherited properties, and more importantly don't recognize each other as siblings. So I think that's the first thing to address.

Let's assume the following here forward (no margins, no positioning):

/*------------------------
Default grid
-------------------------*/

/*------------------------
Columns
-------------------------*/

.has-2-columns .col {
  flex: none;
}

.has-2-columns .col {
  width: 49%;
}

/*------------------------
Logo
-------------------------*/

.site-title {
  background: #ccc;
}

/*------------------------
Main navigation
-------------------------*/

.main-navigation { background-color: lightgrey;}

.main-navigation ul {
  display: inline-flex;
  list-style: none;
  padding: 0;
  margin: 0;
}

.main-navigation ul li { }

.left-menu {
  text-align: left;
}

.left-menu li {}

.right-menu {
  text-align: right;
}

.right-menu li {}

.site-header {
  display: flex;
  flex-flow: row wrap;
  background-color: pink;
}

Demo

Home

About

Contact

Store

Making them siblings can assistant in limiting any crutches we have on margins and positioning by granting them situational awareness to one another now.

This is also a good time to practice good standards when it comes to classes. Since we stripped all the classes we no longer need, we aren't styling multiple elements anymore, so we can change their selector to an id.

Additionally, let's take advantage of what we learned about direct descendants and apply that now by making the
 a direct sibling to both lists as follows:

/*------------------------
    Main navigation
    -------------------------*/

#main-navigation {
  background-color: lightgrey;
}

#main-navigation ul {
  display: inline-flex;
  list-style: none;
  padding: 0;
  margin: 0;
}

#site-header {
  display: flex;
  flex-flow: row wrap;
  background-color: pink;
}

Home

About

Demo

Contact

Store

Your needs will vary depending on the project, but this particular example we don't have anything else but the navigation so we are going to promote the  to be the flex parent. In doing this we can take advantage of align properties, justify properties and of course the other flex benefits. The 2 key properties are align-items which (on flex-direction: row) it centers the children vertically in our case, and justify-content which you seem to be familiar with. These 2 properties alone handle everything you've used margins for as intended.

#main-navigation {
 display: flex;
 flex-flow: row wrap;
 align-items: center;  /* center the elements (vertically for this axis) in the parent space */
 justify-content: space-between;
}

#main-navigation ul {
  display: inline-flex;
  list-style: none;
  padding: 0;
  margin: 0;
}
#main-navigation li {
  padding: 0 10px;
}

/* irrelevant */
#site-header {
  background-color: pink;
}

Home

About

Demo

Contact

Store

So that's one way to get your desired outcome on a fundamental level

..... but wait, mobile first right? Naturally, a simple media query can help you adjust things as you wish, that will be arbitrary to your styling needs, but here is a brief example that makes the previous example responsive friendly:

#main-navigation {
 display: flex;
 flex-flow: row wrap;
 align-items: center;  /* center the elements (vertically for this axis) in the parent space */
 justify-content: space-between;
}

#main-navigation ul {
  display: inline-flex;
  list-style: none;
  padding: 0;
  margin: 0;
}
#main-navigation li {
  padding: 0 10px;
}

@media only screen and (max-width: 396px) {
  #main-navigation {
    flex-flow: column nowrap;
  }

  #main-navigation h1 {
    order: -1;
  }
}

/* irrelevant */
#site-header {
  background-color: pink;
}

Home

About

Demo

Contact

Store

Notice how in that example, the
 element has an order of -1. Flex assigns '0' to an element as the default value. Therefor -1 gives specificity to those elements without needing to change every single one to [..1,2,3 etc]

And if you REALLY REALLY don't feel well about including it there after all that, we can kind of hack it there:

#main-navigation {
  padding: 10px;
}

#main-navigation ul {
  display: flex;
  flex-flow: row wrap;
  align-items: center;
  /* center the elements (vertically for this axis) in the parent space */
  justify-content: space-evenly;
  list-style: none;
  padding: 0;
  margin: 0;
}

#branding {
  font-size: 1.75rem;
}

@media only screen and (max-width: 396px) {
  #main-navigation ul {
    flex-flow: column nowrap;
  }
  #branding {
    order: -1;
  }
}

/* irrelevant */

#site-header {
  background-color: pink;
}

Home

About

Demo

Contact

Store


Optimize nested loops for counting the total number of selections

using namespace std;

Don't do this.  We have namespaces for a reason, you know.  And we seem to be missing the necessary Standard Library headers <iostream> and <cstdio>.

    int n, m, i, j, m = 0, sum = 0;

These variable names tell us nothing about what they are used for.  Please use more expressive names.

    cin >> n >> m;

When reading from a stream such as std::cin, it's vital to check that the conversion was successful before using the values.  That could be as simple as
if (!cin) {
    return EXIT_FAILURE;
}

    int *a=new int[n];

Prefer a standard container (e.g. std::vector).

    for (i = 0; i < n; i++) {

If we had a std::vector, we could have avoided hand-coding this loop:
auto a = std::vector{};
a.reserve(n);
std::copy_n(std::istream_iterator<int>(std::cin), n, a.begin());

        scanf("%d", &a[i]);

Why are we mixing C++ streams and C stdio?  It's better to use just one (preferably the streams).  Again, we're missing the test whether the conversion was successful.


Encoding text to keypresses on old phone keyboard (0-9*#)

Library combinators and list comprehension syntax allow much collapsing of your code, and many of your type aliases and oneliners do not deserve a name, except perhaps for those at the bottom because you export them.

type KeyboardLayout = [(Char, [Char])]

stringToKeyTaps :: KeyboardLayout -> String -> [(Char, Int)]
stringToKeyTaps kmap cs =
  [ (label, index + 1)
  | c <- cs
  , c' <- ['^' | isUpper c] ++ [toLower c]
  , Just (label, index) <- asum $ (map . traverse) (elemIndex c') kmap
  ]

fingerTaps :: [(Char, Int)] -> Int
fingerTaps = sum . map snd

mostPopularElement :: (Ord a, Eq a) => [a] -> a
mostPopularElement = head . head . sortOn length . group . sort


An attempt at a simple type safe python enum

def typeSafeEnum(enumName, *sequential):

Python convention is lowercase_with_underscores for functions and parameters. Although since this is a type factory its not totally clear what convention should appply. I also wonder if passing the enum values as a list might be better.

    topLevel = type(enumName, (object,), dict(zip(sequential, [None] * len(sequential))))

There is no point in the dict you are passing since you just setattr all the enums in place already. Here you set all the enum values up with None initially and then fill them in. Why? I can also see why you call this topLevel but its not an immeadiately obvious name

    vals = map(lambda x: type(x,(topLevel,),{}), sequential)

List comprehensions are generally preffered to calling map with a lambda. But also, why? Just do this in the for loop. You don't gain anything by having it done in a map and then zipping over it.

    for k, v in zip(sequential, vals):

I suggest longer less abbreviated names

        setattr(topLevel, k, v())
    return topLevel


Image upload handler with random filename generator and postprocessing

Extract Code to Function and avoid goto

First of all, I would extract this code to it's own function, and then I would use a while loop looking something like this:

private function getUnusedRandomFileName($extention) {
    $name = $this->random_name() . $extention;

    while(file_exists($this->img_path . $name)){
        $name = $this->random_name() . $extention;
    }

    $return name;
}

To avoid the two duplicate lines, you could also use do-while:

private function getUnusedRandomFileName($extention) {
    do {
        $name = $this->random_name() . $ext;
    } while (file_exists($this->img_path . $name));
    return $name;
}

Or, since you now have a function, you could return:

private function getUnusedRandomFileName($extention) {
    while(true){
        $name = $this->random_name() . $ext;
        if(!file_exists($this->img_path . $name)){
            return $name;
        }
    }
}

Or use recursion:

private function getUnusedRandomFileName($extention) {
    $name = $this->random_name() . $extention;
    if (file_exists($this->img_path . $name)) {
        return getUnusedRandomFileName($extention);
    } else {
        return $name;
    }
}

So there are many methods to solve this without goto. I like the third best, but choose the one you like.

Misc

More functions: in addition to the getUnusedRandomFileName function, I would also add a createThumbnail function, and possibly createImageFrom and writeImageTo, for the first and second switch statement.
Paths: at one point you have $this->img_path . $name, and at another you have $this->args['base_url'].'img/'. $name. Do these mean the same thing? Is $this->img_path the same as img? In that case use it everywhere, otherwise it will cause bugs when changed.
The image type is completely user controlled, so $image_type = $_FILES[$img_name]['type']; will be whatever the user wants it to be; exif_imagetype is also bypassable. So it seems that the in_array($ext,$valid) is currently the only part that prevents attacks. I would add a comment stating this, just in case the code is changed later on.


As a minor note you could change this.documents = unmodifiableList(new ArrayList<String>(documents); to this.documents = Collections.emptyList();


Randomly re-partition 1Dimensional List to 2Dimensional

for (int i = 0; i < OneDimensionalLists.Count; i++)
{
    var random = new Random(seed);
    int next = random.Next(10, 30);
    ...

Have you checked the value of next on the various iterations? I can't see seed changing anywhere in this code. Assuming it remains the same, random.Next() will return the same value each time. Unless this is intentional, create the Random(seed) outside of the loop.


Is there a better way to combine these arrays?

Using in_array can be droped one foreach

$result = array();
foreach ($array['Permission'] as $key => $value) {
  if (in_array($key, $array['Moduleid'])) {
     $result[$key] = $value;
  }
}


I see a number of things that may help you improve your code.

Fix the formatting

The code has an inconsistent format, with varying indentation and brace placement.  To make your code easier to read, you should choose a style and apply it consistently.

Avoid confusing branching constructs

The code currently contains this:

for (auto& vec: vecTemp) {
    if (indexCol >= vec.size())
        continue;
    else {
        mapAlphabet[(char)index] = vec.at(indexCol);
        index++;
    }
}

(with the formatting fixed).  There are several problems with this.  The first is that the control flow is confusing.  It can be made much simpler:

for (auto& vec: vecTemp) {
    if (indexCol < vec.size()) {
        mapAlphabet[(char)index] = vec.at(indexCol);
        index ++;
    }
}

Use appropriate types for variables

The next problem with that code is that it uses an old C-style cast to turn index into a char.  In fact, it's cast to a char just about every time it's used.  Why not just declare it as a char in the first place and remove the casts?

Eliminate "magic numbers"

Instead of using numbers such as 97 and 123 as with this code:

for (int i = 97; i < 123; ++i) {
    char c = (char) i;
    std::size_t found = mKeySecret.find(c);

it would make the code a lot easier to understand if we used the appropriate type of variable and used character constants like this:

for (char c = 'a'; c <= 'z'; ++c) {
    std::size_t found = mKeySecret.find(c);

Use boolean results directly

Rather than this:

std::size_t found = mKeySecret.find(c);
if (found != std::string::npos) {
    mapOriginAlphabet[c] = false;
} else {
    mapOriginAlphabet[c] = true;
}

The code would be much shorter and clearer written like this:

bool found = mKeySecret.find(c) != std::string::npos;
mapOriginAlphabet[c] = !found;

Or possibly this:

mapOriginAlphabet[c] = mKeySecret.find(c) == std::string::npos;

Understand standard template library containers

The code for encrypt contains these lines:

for (auto& x: strOrigin) {
    ret += mapAlphabet[x];
}

This seems to do the right thing, but in fact, it inserts non alphabetic characters into the mapAlphabet which is not the desired behavior here.  Instead, you should use mapAlphabet.at(x) like this:

for (const auto& x: strOrigin) {
    try {
        ret += mapAlphabet.at(x);
    } catch (std::exception &e) {
        // ignore out of range inputs
    }
}

Use const where practical

Performing an encryption or decryption with a given keyword should not alter the underlying transpositioncipher object, so those should be made const.

Prefer const & as function arguments

Several of the functions take a std::string as an argument, but should probably be const std::string & instead to avoid the pointless duplication of a string.  The constructor and removeDuplicates are two such places, as are encrypt and decrypt.

Re-examine your algorithm

What you have implemented is not a transposition cipher, but a substitution cipher in which the ciphertext alphabet is derived by a transposition.  Encryption and decryption could be done with an inverse pair of std::unordered_map objects which may give slightly better performance.

Don't keep variables that are not needed

The vecOrder and mapOriginAlphabet variables are only need during object construction, so they should not be permanent data members of the object.  They could be created and destroyed as the map is being constructed.  Better yet, don't use them at all, as shown in the next suggestion.

Rethink your algorithm

Ultimately, the goal of the constructor is to create a substitution map based on the keyword.  The procedure is to eliminate duplicate letters in the keyword and then to create a table that includes all of the letters, rearranged according to the keyword.  For example, the keyword "bongo" would be reduced to "bngo" and then your vecTemp would look like this:

'b', 'o', 'n', 'g',
'a', 'c', 'd', 'e',
'f', 'h', 'i', 'j',
'k', 'l', 'm', 'p',
'q', 'r', 's', 't',
'u', 'v', 'w', 'x',
'y', 'z',

We then read down the columns according to the alphabetic order of the letter at the top of each column and create the substitution map:

a = b
b = a
c = f
d = k
e = q
f = u
g = y
h = g
i = e
j = j
k = p
l = t
m = x
n = n
o = d
p = i
q = m
r = s
s = w
t = o
u = c
v = h
w = l
x = r
y = v
z = z

I think that if you ponder it a while longer, there is perhaps a more direct way to derive the map. Instead, you could start with something like this:

std::string &delete_duplicates(std::string &str, size_t len) {
    for (size_t i=0; i < len; ++i) {
        str.erase(std::remove(str.begin()+i+1, str.end(), str[i]),
            str.end());
    }
    return str;
}

Then in the constructor, you could have this:

delete_duplicates(keyword, keyword.size());
std::string alphabet{keyword + "abcdefghijklmnopqrstuvwxyz"};
delete_duplicates(alphabet, keyword.size());

That gives the linear string that represents the two dimensional array shown above. Remap them into vector of strings and sort:

std::vector<std::string> columns(keyword.size());
for (size_t i=0, col=0; i < alphabet.size(); ++i) {
    columns[col++] += alphabet[i];
    if (col >= columns.size()) {
        col = 0;
    }
}
std::sort(columns.begin(), columns.end());
// now replace the alphabet
alphabet.clear();
for (auto &word : columns) {
    alphabet += word;
}

Now you can construct an encryption map (and a decryption map, if you like) by simply linearly assigning each letter of the "new" alphabet.