Shopping List Application (Work in Progress)

Welcome to Code Review SE!

I'll list some things I found while skimming over your code. This is unordered, and by no means exhaustive.

Most programming languages have a certain style guide associated with them. In the case of Python, it's PEP-8. It is in your best interest to comply with the points outlined there, as doing so will significantly improve readability.

Keep vertical whitespace to a minimum. Blank lines can aid in grouping related pieces of code together1, but in my opinion, you've gone a bit overboard. Having just two blank lines in between top-level function definitions is recommended.
Your function and variable names follow the PEP-8 naming conventions2. Good job, lots of people get this wrong at first.
Whenever you find yourself using an escaped quote character (\' or \"), you can simply surround the string with the other type of quotes.3 This makes the code more readable and reduces the chances of getting syntax errors. To take an example from the piece of code you wrote:

print('It\'s time to go shopping!')

... becomes:

print("It's time to go shopping!")

It's good practice to separate arguments to functions by a single space.4 An example from shopping_list():

print('Current cart total: ',sum(item_dict.values()))

... becomes:

print('Current cart total: ', sum(item_dict.values()))

Block comments should start with a space.5

It's nice that you added comments, but most of them are plain wrong. Never add comments that are simply a rewording of the code, and always assure your comments are up to date and correct. Let's go over your comments one by one.

Lines 3 through 6:

#create shopping list with automatic calculation

def display_help():

... not even close. I guess you reordered your functions at some point and forgot to update this comment.
Lines 14 through 17:

#create a list with the items needed
#

def clear_screen():

... the same goes for this comment. You don't create a list here. You don't do anything here.
Lines 22 through 26:

#Create function to change values of current items or update price of items in the cart

def shopping_list():

... finally, a comment that's in the right place. Unfortunately, this one falls under the 'documenting self-documenting code' category.6 Nitpick: you normally don't create a function, but define it.
...

I'm happy you found a way to avoid global variables, but nesting functions is rarely the right solution. show_items() should really be a top-level function, taking one argument.
By using f-strings, you're greatly limiting portability. I'd make a safe bet and use str.format() for now.
Let's see what happens when I exit the program:

Welcome! What would you like to do?
> EXIT
Goodbye

So far, so good. How about quitting from the 'SHOP' submenu?

Please enter an item: QUIT
You have added QUIT to your list

Price of QUIT:

Whoops, that's not what I was hoping to see. The help message clearly says:

'QUIT' to exit the program

Peculiar. Now that we're stuck with having to add a new item, let's go through with it and then exit.

Price of QUIT: 50
You entered 50.0 as the price of QUIT

You now have 1 items in your list.

The total currently on your cart is 50.0
Would you like to add more items?(Y/N) n
Here's your cart and your total:

Traceback (most recent call last):
File "ttt.py", line 86, in <module>
    begin_attempt()
File "ttt.py", line 78, in begin_attempt
    shopping_list()
File "ttt.py", line 64, in shopping_list
    raise KeyboardInterrupt('Goodbye')
KeyboardInterrupt: Goodbye

Oh my, that's ugly.

On a more serious note, there should only be one way to exit the program, and it should not be by means of an uncaught exception. You could do this a number of ways:

Put all of the prompts in a huge while-loop, then break from the loop when the user wants to exit. This gets messy very quickly. Avoid it.
Put all of the prompts in a huge while-loop, then call a function to exit. This is a much better alternative.

As an aside, it's almost never a good idea to raise a KeyboardInterrupt manually. Even a RuntimeError would be a better fit, but as I explained, cleanly exiting the script is ideal. The sys module provides sys.exit(), which is the best way of quitting Python scripts. Don't use exit(). It is a special function and should only be used in the Python REPL.
The main menu is broken:

    =======> Help <=======
    'HELP' to display this menu
    'START' to start creating your shopping list
    'SHOW' to display your current items
    'QUIT' to exit the program

> start
> show
> SHOW
> :(

try / except-constructs should capture the least amount of code possible. A clear violation of this principle, starting on line 52:

try:
    ... [12 lines skipped]
except ValueError:
    print('Please enter a number')

... the try-block only needs to encompass line 53, because that's the only line that could raise a ValueError.
On line 60, the input validation is off. The prompt suggests 'Y' and 'N' are valid inputs, but:

if add_more_items == 'Y'.lower():

... indicates it is not. If you want to do case-insensitive comparisons, call str.lower(), like you did in other instances. Alternatively, you could call str.casefold(), which also handles special characters like 'ß':

>>> "Straße".lower()
'straße'
>>> "Straße".casefold()
'strasse'

shopping_list is a bad function name. Function names are typically verbs. Maybe play_shopping_game?
String concatenation is in many ways inferior to string formatting. It's slower, harder to read, and less versatile: each argument needs to be casted to str if it is not already a string. Always prefer string formatting over concatenation.

References

1 PEP-8: Blank Lines

2 PEP-8: Naming Conventions

3 PEP-8: String Quotes

4 PEP-8: Whitespace in Expressions and Statements

5 PEP-8: Comments: Block Comments

6 Don't get me wrong, documenting functions is very important. The 'create a function' part is too verbose nevertheless. If you want to add formal documentation to functions, add docstrings! Docstrings are multiline strings placed below a function or class signature. For example:

def add(a, b):
    """Return `a` + `b`. Both arguments must be numbers."""
    return a + b

You can access the docstring as the object's __doc__ attribute:

>>> add.__doc__
'Return `a` + `b`. Both arguments must be numbers.'

... and in the Python REPL, you can use the built-in help():

add(a, b)
    Return `a` + `b`. Both arguments must be numbers.

There's also an official style guide for docstrings, called PEP-257.


TCP client and server supporting six simple commands

I would recommend that you read PEP 8, the Python style guide.

PEP 8 says:

  Use 4 spaces per indentation level.

You use four spaces in some places, but in others you use eight.  At the very least you should be consistent, but it is best if you consistently use four spaces.  In fact, looking at your code, your indentation is completely shot.  I spy with my little eye an IndentationError in the elif data.startswith('REQDATE'): block.  Your break statements in those if blocks are not consistent either.

print("sending: " + str(data))

One line up you defined data as a string.  Python objects don't just drift into new types.  They don't change unless you change them.  You don't need the str part here.  Just do this:

print("sending: " + data)

You convert data to a string in several other places, but there also it is useless.  That's like translating a German sentence into English and then translating that sentence into English every time I want to use it.  What is the purpose of translating English into English?

if True:

True is always True, so that if block will always be executed.  Why do you use an if block if you always want to execute what is inside?

if data.startswith('HELO'):
    try:
        c.sendall(...)
    except:
        c.sendall(...)
    break
elif data.startswith('REQTIME'):
    try:
        c.sendall(...)
    except:
        c.sendall(...)
        break
...

You have some duplicate code there.  That is, it would be duplicate if you were consistent with what you wanted.  There are two things that change in these: The string given to the first c.sendall() and the string given to the second c.sendall().  I would create a dictionary:

messages = {
    'HELO': (
        "210 HELO " + host + " This is Dalek High Command.  You will obey all orders without question!",
        "510 You are unauthorized! You will be exterminated!"),
    'REQTIME': (
        "220 I obey!  The time is " + time.strftime("%H%:M%:S"),
        "520 The time is unavailable!  Exterminate!"),
    'REQDATE': (
        "230 I obey!  The date is " + time.strftime("%Y/%m/%d"),
        "530 The date is unavailable!  Exterminate!"),
    'ECHO': (
        "240 Data received! " + data.upper(),
        "540 ECHO!  I cannot obey!  Assist!  Assist!  Cannot comply!  Exterminate!"),
    'REQIP': (
        "250 IP has been identified! " + host,
        "550 Alert!  I cannot obey! Your IP cannot be retrieved!"),
}

for key, value in messages.items():
    if data.startswith(key):
        try:
            c.sendall(value[0])
        except:
            c.sendall(value[1])
        break
else:
    if data.startswith('BYE'):
        try:
            c.sendall ("600 Alonzy! Bowties are cool!  See you later!")
        except:
            break

sys.exit()
c.close()

You exit the program and then expect to be able to close c?  Perhaps that's a debugging call that you forgot to take out, but sys.exit() is unnecessary here.

for x in range(0, 5):
    if x == 0:
        data = 'helo'
        s.send(data)
    elif x == 1:
        data = 'reqtime'
    elif x == 2:
        data = 'reqdate'
    elif x == 3:
        data = 'echo'
    elif x == 4:
        data = 'reqid'
    elif x == 5:
        data = 'bye'

s.send(data)
print(str(data))
x = x + 1

I'm guessing that the s.send(data) and below lines were meant to be inside of the for loop.  If they were, there is a much simpler way to do this:

for data in ("helo", "reqtime", "reqdate", "echo", "reqid", "bye"):
    s.send(data)
    print(data)


My own personal preference when outputting things like this is to put the portion where data is actually retrieved in a separate file and then use the alternate PHP structure syntax. While this probably isn't everyone's preferred coding style, in my opinion it makes it easier to structure HTML so that its readable among the PHP. From what I have seen, this appears to be relatively common in templates.

Just a quick once-over your file to show you what I mean:

<?php
require 'DB.php'

try {
    $stmt = $conn->query('SELECT * FROM equipment');
}
catch(PDOException $e){
    echo'ERROR: ' . $e->getMessage();
    die();
}

?>

    Equipment Type
    Unit Number
    Last Updated
    CurrentHours
    Scheduled PM

<?php while($row = $stmt->fetch()): ?>

    <?php echo htmlspecialchars($row['equipType']); ?>
    <?php echo htmlspecialchars($row['unitNumber']); ?>
    <?php echo htmlspecialchars($row['lastUpdate']); ?>
<?php if ($row['nextPM'] - $row['currentHours'] > 100): ?>
    <?php echo htmlspecialchars($row['currentHours']); ?>
    <?php echo htmlspecialchars($row['nextPM']); ?>
<?php elseif ($row['nextPM'] - $row['currentHours'] < 100 && $row['nextPM'] - $row['currentHours'] > 50): ?>
    <?php echo htmlspecialchars($row['currentHours']); ?>
    <?php echo htmlspecialchars($row['nextPM']); ?>
<?php else: ?>
    <?php echo htmlspecialchars($row['currentHours']); ?>
    <?php echo htmlspecialchars($row['nextPM']); ?>
<?php endif; ?>

<?php endwhile; ?>

Again, if I were doing this I would separate that top half into another file and have that file include your "template" which would output the actual HTML. You could also use a template engine like Savant3 to make the separation a little cleaner and the templating better.

Demonstration with savant3:

Your main file (index.php perhaps?):

<?php
require 'DB.php'
require_once 'Savant3.php'
$tpl = new Savant3();

try {

    $stmt = $conn->query('SELECT * FROM equipment');
    $tpl->data = $stmt;
}
catch(PDOException $e){
    echo'ERROR: ' . $e->getMessage();
    die();
}

$tpl->display('table.tpl.php');

?>

Then in your template file (table.tpl.php in this example):

    Equipment Type
    Unit Number
    Last Updated
    CurrentHours
    Scheduled PM

<?php foreach($this->data as $row): ?>
    <?php $class = "bad";
    if ($row['nextPM'] - $row['currentHours'] > 100) {
        $class = "good";
    }
    elseif ($row['nextPM'] - $row['currentHours'] < 100 && $row['nextPM'] - $row['currentHours'] > 50) {
        $class = "soon";
    }
    ?>

    <?php echo htmlspecialchars($row['equipType']); ?>
    <?php echo htmlspecialchars($row['unitNumber']); ?>
    <?php echo htmlspecialchars($row['lastUpdate']); ?>
    <td class='<?php echo $class; ?>'><?php echo htmlspecialchars($row['currentHours']); ?>
    <td class='<?php echo $class; ?>'><?php echo htmlspecialchars($row['nextPM']); ?>

<?php endforeach; ?>

Note that I changed the while into a foreach because I personally don't like doing an assignment and comparison in the same statement. You can foreach over a PDOStatement (as far as I know) just as well as you can fetch from it.

EDIT: Also, you don't necessarily need to prepare the statment with the PDOs if there are no arguments. Of course, that's all up to preference again. If you have arguments, though, definitely use the prepared statements.


Exclusive and inclusive filtering of attributes

To @Tushar's point, those 2 code blocks are not similar. In fact, I would advise you to turn that function in to 2 functions with a better name. Especially since your function optionally depending on include modifies data which is not a good design. It should either always generate a new object, or always modify data. Probably it should always generate a new object.

Furthemore for greater flexibility, I would not check for attributes.length but for attributes.forEach, this way you know for sure the function/method is defined.

In Lodash the first function would be called pick, and the second function would be omit.

Thinking about this, if you are always going to build a new object, you could remove repetitive coding:

function filter(attributes, data, include) {
    'use strict';

    let keys = Object.keys(data),
        res = {};
    //Turn attributes into an array if needed
    attributes = (typeof attributes === 'string') ? [attributes] : attributes;
    keys.forEach(key => {
        //If its an attribute we include, get it
        //If its an attribute we dont exclude, get it
        if ((include && attributes.indexOf(key) != -1) ||
            (!include && attributes.indexOf(key) == -1)) {
            res[key] = data[key];
        }
    });
    return res;
}


Not to be too blunt; but, you're going about this the wrong way. Look into the command line option -MMD for GCC, specify it when compiling your source; and, retain the inclusion statement for dependencies.

Also, no need for a default target. The first target is the default target.

An example:

Gpp = g++
srcs = $(wildcard *.cpp)
objs = $(srcs:.cpp=.o)
deps = $(srcs:.cpp=.d)

test: $(objs)
    $(Gpp) $^ -o $@

%.o: %.cpp
    $(Gpp) -MMD -MP -c $< -o $@

.PHONY: clean

# $(RM) is rm -f by default
clean:
    $(RM) $(objs) $(deps) test

-include $(deps)


K&R Exercise 1-13. Printing histogram of word lengths (horizontal variant)

K&R C requires all variables to be declared at the start of their enclosing block.  This is a bad habit to learn: it's much safer to declare variables where they can be initialised:
/* these can already be initialised where they are declared */
int state = OUT;
int histo[MAXLEN+1] = { 0 };  /* C90 */
int counter = 0;

/* reduce scope, and never have uninitialized value */
for (int j = 0; j < histo[i]; ++j)  /* C99 */

We could remove the need to subtract 1 from the length when updating histo if we reserve the first element for long words instead of the last:
        if (state == IN && counter > 0) {
            if (counter <= MAXLEN)
                ++histo[counter];
            else
                ++histo[0];
        }

We obviously need to make a corresponding change to the printing:
for (int i = 1;  i <= MAXLEN;  ++i) {
    if (MAXLEN < 10)
        printf(" %1d | ", i);
    else if (MAXLEN < 100)
        printf(" %2d |", i);
    else
        printf(" %3d |", i);
    for (int j = 0;  j < histo[i];  ++j)
        putchar('*');
    putchar('\n');
}

We can avoid the if/else chain on MAXLEN in this loop, by choosing the formatting string in advance:
const char *format = "";
if (MAXLEN < 10) {
        format = " %1d | ";
} else if (MAXLEN < 100) {
        format = " %2d | ";
}  else {
        format = " %3d | ";
}

for (int i = 1;  i <= MAXLEN;  ++i) {
    printf(format, i);
    for (int j = 0;  j < histo[i];  ++j)
        putchar('*');
    putchar('\n');
}

That might not look like an improvement, but with a small change, we can use the same format string to insert > for the over-long words, too:
const char *format = "";
if (MAXLEN < 10) {
        format = "%c%1d | ";
} else if (MAXLEN < 100) {
        format = "%c%2d | ";
}  else {
        format = "%c%3d | ";
}

for (int i = 1;  i <= MAXLEN;  ++i) {
    printf(format, ' ', i);
    for (int j = 0;  j < histo[i];  ++j)
        putchar('*');
    putchar('\n');
}

/* over-long words */
printf(format, '>', MAXLEN);
for (int j = 0; j < histo[0]; ++j)
    putchar('*');
putchar('\n');

Going beyond the expected level of knowledge, we could even compute the necessary length, and pass it using %*d:
int width = 1;
for (int i = MAXLEN;  i >= 10;  i /= 10) {
    ++width;
}

for (int i = 1;  i <= MAXLEN;  ++i) {
    printf(" %*d | ", width, i);
    for (int j = 0;  j < histo[i];  ++j)
        putchar('*');
    putchar('\n');
}

/* over-long words */
printf(">%*d | ", width, MAXLEN);
for (int j = 0; j < histo[0]; ++j)
    putchar('*');
putchar('\n');

That allows us to have non-constant MAXLEN, which will be to our advantage in future when we make this a function.

Whilst the state machine is a good idea, it turns out we don't need to explicitly store state, because counter is always zero outside a word and non-zero once we're in one:
while ((c = getchar()) != EOF) {
    if (c == ' ' || c == '\n' || c == '\t') {
        if (counter > 0) {
            ++histo[counter <= MAXLEN ? counter : 0];
            counter = 0;
        }
    } else {
        ++counter;
    }
}

Did you spot the bug in this loop?  Probably not, because the bug is missing code immediately after the loop.  If the input stream ends during a word, we fail to count it.  We need to repeat the if (counter > 0) test just after the loop, to catch that case.

We have an unusual definition of "word" - in our source code, strings such as ++histo[counter-1]; count as single words.  Even in English text, we'd expect text, to register as a four-character word.  To fix this, we could consider only alphanumerics as word characters, and that could be a good introduction to the functions in <ctype.h>.
while ((c = getchar()) != EOF) {
    if (isalnum(c)) {
        ++counter;
    } else {
        if (counter > 0) {
            ++histo[counter <= MAXLEN ? counter : 0];
            counter = 0;
        }
    }
}

if (counter > 0) {
    ++histo[counter <= MAXLEN ? counter : 0];
}

Enhancement - we could avoid bars going off the right edge of the display, by calculating a scale factor first.  Here's my suggestion:
#define MAXWIDTH 72             /* screen width available for bars */

    double scale = 1.0;
    for (int i = 0;  i <= MAXLEN;  ++i) {
        if (histo[i] * scale > MAXWIDTH) {
            scale = 1.0 * MAXWIDTH / histo[i];
        }
    }

        for (int j = 0;  j < histo[i] * scale;  ++j) { putchar('*'); }

Finally: it's not part of your C code, but there's no need for cat in the test.  We can simply redirect input like this:
./ch1-ex-1-13-01 <ch1-ex-1-13-01.c

Modified code
Applying all my suggestions, I got:
/* Exercise 1-13. Write a program to print a histogram of the lengths of
   words in its input. It is easy to draw the histogram with the bars
   horizontal; a vertical orientation is more challenging. */

/* Solution 1: Horizontal Bars
 * */
#include <ctype.h>
#include <stdio.h>

#define MAXLEN  10  /* Any word longer than this will get counted in the
                       >MAXLEN histogram. */

#define MAXWIDTH 72             /* screen width available for bars */

int main()
{
    int histo[MAXLEN+1] = { 0 }; /* element 0 counts over-length words */

    /* Perform the counting */
    int counter = 0;
    int c;
    while ((c = getchar()) != EOF) {
        if (isalnum(c)) {
            ++counter;
        } else {
            if (counter > 0) {
                ++histo[counter <= MAXLEN ? counter : 0];
                counter = 0;
            }
        }
    }

    if (counter > 0) {
        ++histo[counter <= MAXLEN ? counter : 0];
    }

    /* Calculate sensible scale */
    double scale = 1.0;
    for (int i = 0;  i <= MAXLEN;  ++i) {
        if (histo[i] * scale > MAXWIDTH) {
            scale = 1.0 * MAXWIDTH / histo[i];
        }
    }

    /* how wide are the labels? */
    int width = 1;
    for (int i = MAXLEN;  i >= 10;  i /= 10) {
        ++width;
    }

    /* Write the output */
    for (int i = 1;  i <= MAXLEN;  ++i) {
        printf(" %*d | ", width, i);
        for (int j = 0;  j < histo[i] * scale;  ++j) { putchar('*'); }
        putchar('\n');
    }

    /* over-long words */
    printf(">%*d | ", width, MAXLEN);
    for (int j = 0; j < histo[0] * scale; ++j) { putchar('*'); }
    putchar('\n');
}


Custom login system (PDO, sanitizing, hash)

Well, let's see:

You're using PDO and prepared statements, no risk of SQL injection there. Great!
Your PDO code may throw an Exception (Specifically, a PDOException) at any time, so the whole database code block should be kept inside of the try/catch block.
crypt in on itself isn't 100% secure. See This question for more details.
Database credentials are not constant. They can change over time, and you may want to change the server, change the user, add an additional database etc in the near/far future. The solution is to use functions (or better yet, classes) and pass the credentials as variables, rather then applying them as app-wide constants.


Append to compressed tar file with performance

Indeed, the tarfile package doesn't support appending to a compressed tar.
But I think you can do better than your current attempt.
Instead of extracting the content to disk, you could keep it in memory, write and append to a new compressed file, and finally rename the compressed file.
That way you will write a single temporary file,
instead of many.
The reduced disk I/O should improve the performance.

def append_tar_file(buf, file_name, output_path, replace=True):
    """
    append a buf to an existing tar file if not already there, or if replace=True
    """
    if not os.path.isfile(output_path):
        return

    with tempfile.TemporaryDirectory() as tempdir:
        tmp_path = os.path.join(tempdir, 'tmp.tar.bz2')

        with tarfile.open(output_path, "r:bz2") as tar:
            if not replace:
                if file_name in (member.name for member in tar):
                    return

            if isinstance(buf, str):
                buf = buf.encode("utf-8")

            fileobj = BytesIO(buf)
            tarinfo = tarfile.TarInfo(file_name)
            tarinfo.size = len(fileobj.getvalue())

            with tarfile.open(tmp_path, "w:bz2") as tmp:
                for member in tar:
                    if member.name != file_name:
                        tmp.addfile(member, tar.extractfile(member.name))
                tmp.addfile(tarinfo, fileobj)

        os.rename(tmp_path, output_path)


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

Pass by const reference where practical

In every case that a QString ip is passed, the code could instead use a const QString &ip avoiding pointless multiple copies and also allowing the addition of a const IP address.

Consider large files

Reading the entire file into memory using QTextStream::readAll() can consume a lot of memory if the file is large. If you still want to do this anyway, see the next suggestion.

Don't store the file contents in the object

The object currently stores both the entire contents of the file in two forms: both as QString and as QStringList which isn't really needed.  First, you could pass the QString back as the return value for read(), and then you could have find(), addIP() and write() take that QString as an additional parameter.  Naturally, this should also be passed by const reference.

Reduce object creation where practical

Within the addIP() call, it isn't really necessary to prepend the "\n" to the addendum QString since that could easily simply be added to the static string.  Using all of the previous suggestions and this one, here is one way to write this function:

void SSHConfigFile::addIP(const QString &ip, const QString &fileData)
{
    QString addendum = QString("\n# Added by RigakuSync\n"
                               "Host %1\n"
                               "\tStrictHostKeyChecking no\n"
                               "\tUserKnownHostsFile=/dev/null\n").arg(ip);

    write(fileData + addendum);
}

Consider an alternative class design

The configuration file for your program is really a collection of attributes that each apply to a single Host, so what might make more sense as you expand this program, would be to create a HostConfig class to hold each individual configuration set, and then your SSHConfig class could implement a collection of those.

List all required #includes

I'm sure it is in your code (because it wouldn't otherwise compile) but it would be useful for reviewers to see a full, compilable sample which includes the required #include files.

Sanitize input

At the moment, if an ip QString with leading whitespace is handed to the registerIP() call, it will always add a duplicate entry because the un-trimmed input ip is being compared to the trimmed partial line.  If I were to abuse the program like this, I could make the configuration file grow without limit.

SSHConfigFile sh1;
for (int i=1000000; i; --i)
    sh1.registerIP( " 8.8.8.8" );

Make sure to match file open and close

In the case that the find routine finds a duplicate entry, it leaves the file open.  If it adds a new entry, it leaves the file closed.  This makes it impossible for the calling program to know whether the file is open or closed at the end of the call.  To fix that, (and using the previous suggestions), you could refactor like this:

void SSHConfigFile::registerIP(const QString &ip)
{
    QString fileData = read();
    if (!find( ip, fileData))
    {
        // this is new ip, add it to config file
        addIP( ip, fileData );
    } else {
        file.close();
    }
}

OOP design

Simply stated, in Object Oriented Programming, the nouns in a description become objects and the verbs become methods.  In this case the description is "reads an SSH config file and checks whether an IP exists. If the IP does not exist, the class adds a block for that IP address." so the relevant nouns are:

SSH config file
IP address
block (for IP address)

Verbs are:

read file
check file for IP address
add block for IP address to file

These match pretty closely to the methods in your class, and the IP address is passed in from the calling program.  As I mentioned in a previous point, one could consider creating an alternative design in which each block is a Host object, and the file could be implemented as a host collection (perhaps std::map<IPAddress, Host>) but the decision to do so or not depends on how you're planning to use this.  If the need for the IP block is only transient and static (as you've written it) then it's fine as you have it.  If, on the other hand, other parts of the program will be altering settings in the file or looking them up frequently, the Host object approach may be more natural.

Generally speaking, I think about the interface first.  Ask yourself "How would I like to interact with this thing?"  Then implement that, revealing as few internal details as practical.  Reducing the scope of variables to be as small as possible also helps, so that instead of the old style:

int i;
for (i=0; i < MAX_STUFF; ++i) { ... }

We prefer:

for (int i=0; i < MAX_STUFF; ++i) { ... }

Similarly, for the IP address, we know that it must be passed in to do the work of the registerIP() method.  If it were part of the object, it would uselessly take up memory as long as the object exists.  However, by passing it by const reference (my first suggestion) you minimize its scope to be as small as possible.  For this design, that's a good choice.  However, if you decide to implement as a collection of Host objects, the IP address would necessarily be member data.


Functions are described in the Python tutorial - they are separate blocks of code which take defined inputs (argument values) and provide defined outputs (return values), and usually have a descriptive comment ("docstring") at the top:

def function(argument):
    """A simple function to double things."""
    output = argument * 2
    return output

As to how you can proceed on refactoring your code to use these functions, I suggest you take the following steps:

Step 1: Abstract repeated code into standalone functions:

def get_float_input(prompt, min_, max_):
    """Take valid float input between min_ and max_ from the user."""
    ...

room_width = get_float_input("Enter the room width, it must be between 1m-25m: ", 1, 25)
room_height = get_float_input("Enter the room height, it must be between 2m-6m: ", 2, 6)

You can use this community wiki to help you write the functionget_float_input.

Step 2: Use dictionaries to simplify multiple elifs, and continue to factor out repeats:

def get_str_input(prompt, choices):
    """Take valid string input from the user from items in choices."""
    ...

prompt = "Please choose from a selection of paints: 'Luxury', 'Standard', or 'Economy'."
paint_factor = {"Luxury": 1.45, "Standard": 1.0, "Economy": 0.45}
room_paint = room_total * paint_factor[get_str_input(prompt, paint_factor)]

prompt = "Would you like to use an undercoat? Y/N: "
undercoats = {"Y": 0.5, "N": 0}
room_undercoat = room_total * undercoats[get_str_input(prompt, undercoats)]

Step 3: Organise whole thing into sensible sub-functions that each do one thing:

def room_size():
    """Calculate the size of a room from user input."""
    width = get_float_input(...)
    height = get_float_input(...)
    return width * height

def paint_cost(size):
    """Calculate the cost of paint for a room."""
    prompt = "..."
    paint_factor = {...}
    return size * paint_factor[get_str_input(prompt, paint_factor)]

def undercoat_cost(size):
    """Calculate the cost of undercoat for a room."""
    prompt = "..."
    undercoats = {...}
    return size * undercoats[get_str_input(prompt, undercoats)]

Step 4: Write one function to bring the rest together:

def main():
    size = room_size()
    total_cost = paint_cost(size) + undercoat_cost(size)
    print("The total cost of painting this room is £{0:.2f}".format(total_cost))

Step 5: Add a call at the bottom of your script to set the whole thing off:

if __name__ == "__main__":
    main()

(see this question if you don't know what that comparison does).

Throughout: Follow the Python style guide, PEP-0008.


Use this code to directly reference and open:

Set NS = myolApp.GetNamespace("MAPI")
NS.Logon
Set myAppt = NS.GetItemFromID(EntryID)
myAppt.Display

Works like a dream.


Simplified light Serialize/Deserialize to/from JSON for .NET

Frame challenge

  I was trying to avoid "complexity", so get rid of 3rd part libs

Although it's not strictly code review, I would like to start by challenging this goal. There are many many official Microsoft libraries with dependencies on Newtonsoft.Json. (See this answer on our software engineering sister site).

Core code

    public static string ObjectToJson(object o, Type t, Type[] pTypes = null)

This absolutely needs documentation comments explaining what t and pTypes are for. As a maintenance programmer this signature is unhelpful on two counts:

I have no idea why I need to pass types at all. If ObjectToJson needs the type of the object for some reason it can call o.GetType().
The names are not helpful. I'm guessing that t is the type of o, but that's a pure guess. As for pTypes, is that Hungarian notation for "pointer to type"? That has no place in C# code unless you're using unsafe and actual pointers (and even there the name should tell you what the variable is for and not just what its type is).

With respect to point 1, I would suggest that in addition to improving the names and adding documentation you consider two further refactorings: either making t an optional parameter with default null and calling o.GetType() if necessary; or changing the signature to public static string ObjectToJson<T>(T obj, IEnumerable<Type> whateverPTypesShouldBeCalled) so that the compiler can infer the type but the caller can impose a supertype if that's necessary for some bizarre reason. (In case you don't know: you can use typeof(T) with T a type variable to get a Type object).

        DataContractJsonSerializer serializer = (pTypes != null ? new DataContractJsonSerializer(t, pTypes) : new DataContractJsonSerializer(t));

Might it make more sense to use new DataContractJsonSerializer(t, pTypes ?? Enumerable.Empty<Type>())?

        MemoryStream mStrm = new MemoryStream();
        ...
        using (var sr = new StreamReader(mStrm, Encoding.UTF8))

This is inconsistent: . I would favour the approach of always using using with IDisposable, even when you know that it doesn't use any unmanaged resources.

A comment explaining why Encoding.UTF8 is correct would be an improvement.

    public static object JsonToObject(string json, Type t, Type[] pTypes = null)
    {
        DataContractJsonSerializer serializer = (pTypes != null ? new DataContractJsonSerializer(t, pTypes) : new DataContractJsonSerializer(t));
        using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
        {
            return serializer.ReadObject(stream);
        }
    }

I think all of the comments on ObjectToJson apply equally to JsonToObject with one exception: this time the signature makes a much stronger argument for use of generics. As it stands you probably have to cast the return value almost every time you use this method.

Usage example

This is again marginally off-topic, so I won't do a detailed review of the example usage code, but I think it's important to address a couple of points.

    private WebRequest createRequest(string pAction, string pFormValues)

Every caller of this method is expected to compose pFormValues. That's the antithesis of Don't Repeat Yourself. The method which factors out the commonalities of requests should be the one place which composes the query string, and unlike the example

            string formValues =
                "&playerId=" + this.LogonInfo.userId.ToString() +
                "&createdBy=" + pMyGames.ToString() +
                "&tookPartIn=" + pGamesITookPartIn.ToString() +
                "";

it should take care to escape the values.

            WebRequest request = createRequest("myGamesList", formValues);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                string responseText = sr.ReadToEnd();

                if (responseText.Contains("\"errType\":"))

Again, I would hope that the web service on the other end is consistent enough that handling the response can be done in one place rather than being repeated for every single call. And I would hope that it uses HTTP well enough that you don't have to do heuristic guessing to figure out whether there was a problem. Instead of looking for "errType": it should switch on response.StatusCode.

        WebRequest request = WebRequest.Create(this.ServerUrl + "?action=" + pAction);

        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = pFormValues.Length;

I find it bizarre that the form values are split between the URL and the request body.


Retaining and passing data between Activities

Fixing a NullPointerException is not under the scope of Code Review, but you should be able to solve that problem by looking at a previous answer of mine where I'm describing How to make a singleton in Android. This might fix your problem. (The short answer is: Use the built-in Application class that Android manages for you)

I have some other comments regarding your questions:

Avoid the Singleton pattern in Android everywhere.
I personally haven't used Parcelable, but I believe it is the recommended approach. If you think implementing it would violate Single Responsibility Principle, then create a delegating wrapper object that implements Parcelable and just more or less stores a reference to the real object.
Or serialize things using the Jackson Library (I wouldn't do this for the simple task of passing data between activities though)
Another alternative for you is to use Fragments. By using fragments properly, you could keep the Post state in your activity, and let the Fragments use a callback on your activity to save parts of the post step-by-step, until it is finally finished in which case you perform the final save of it.

As for the rest of the code in your question, I got just a few comments:

DataHolder is a too generic name. What kind of data is it holding? Sooner or later you might end up with multiple DataHolders.
What if your mediaType would accidentally end up with the value 4? Use an enum to make sure that doesn't happen. And to make your code better. Limited alternatives should always point you to an enum.

public enum MediaType {
    PHOTO, VIDEO, TEXT, PLACE;
}


Periodically comparing the play count of two Last.FM users

I don't see why you say <- "decreases readability", but you could line them up if you think that helps (this style is typical of Haskell programmers)

main = forever $ do
  diff      <- user1 `subtractCounts` user2
  timestamp <- formatTime defaultTimeLocale dateFormat <$> getZonedTime
  homeDir   <- getHomeDirectory
  let logMessage  = printf "%s %d\n" timestamp diff
      logFilePath = homeDir </> logFile
  appendFile logFilePath logMessage
  threadDelay $ 10^6 * 60 * timeDelay -- in microseconds

subtractCounts = liftM2 ((-) `on` fromMaybe 0) `on` getPlayCount
dateFormat     = "[%s] %D %H:%M"

<- is a visual cue that the thing on the right might to perform an effect before producing a result and binding it to the name on the left.

Note that the type annotation on logMessage is unnecessary. Because it is used as the second argument to appendFile it will be inferred to be String.

I personally might make a few more refactorings, but they aren't really necessary:

logMessage :: String -> Integer -> String
logMessage  = printf "%s %d\n"

(f .: g) x y = f $ g x y

subtractCounts = liftM2 ((-) `on` fromMaybe 0) `on` getPlayCount

main = forever $ do
  homeDir <- getHomeDirectory
  let logFilePath = homeDir </> logFile
      logDiff     = appendFile logFilePath .: logMessage
  forever $ mainLoop logDiff

mainLoop logDiff = do
  diff      <- user1 `subtractCounts` user2
  timestamp <- formatTime defaultTimeLocale "[%s] %D %H:%M" <$> getZonedTime
  logDiff timestamp diff
  threadDelay $ 10^6 * 60 * timeDelay -- in microseconds

The type signature on logMessage is probably unnecessary, but imho it's a good idea to give it an explicit signature if you are using the result of printf as a function, rather than a String or IO ().


Spawning random small cubes in a big invisible cube using Unity C#

Why does SpawnSmallCubes() generate only a single cube?
if(cube.GetComponent<Renderer>().material.color.a <= 0) this line is unecessary
GetComponent() calls can be reduced by holding onto the Renderer instance, assuming you aren't swapping it out
smallCubes.ToArray() conversion is unecessary
FadeOutCube() also spawns the cubes. This isn't obvious from the naming


Your assessment is correct, the emailList null checks are redundant in that block.

I would recommend that you use the "FindBugs" tool to perform static analysis on your code. It is available as a plugin to Eclipse, and other tools too. FindBugs would clearly indicate and mark all instances where these problems happen, and also a bunch of other things too.

Additionally, I would neaten things up by pulling just one final local variable for the response.getOutputStream() too. Additionally, you should be using generics, and enhanced-for (for-each) loops over your emailList.

Summarizing this would be:

...
else if ((emailList != null) && (emailTest != null)
              && (emailTest.compareTo(IParameterNames.EMAIL_GO) == 0))
         {

            PrintOutputStream respos = response.getOutputStream();
            respos.print("...blah blah blah...");
            respos.print("...blah blah blah...");
            respos.print("...blah blah blah...");

            respos.print(emailList.size());

            respos.print("...blah blah blah...");
            respos.print("...blah blah blah...");

            respos.print("...blah blah blah...");

            for (EmailMessage email : emailList) {
                if (email != null) {
                  respos.print(outputEmailAddressAsHTML(email, i).toString());
                }
            }

            respos.print("..lots.of.blah blah blah...");
          }


Thread-safe message queue without mutex in C

With a size of 2, your 'queue' can hold only one item, so it is not really a queue.  If
you increase the size to 8 (say) you now really have a queue, but your tests don't
work.

You seem to define send and recv as follows:

send indicates the 'slot' holding the most recently entered data (queue not empty).
recv indicates the 'slot' before the oldest data in the queue (queue not empty).
if send == recv  the queue is empty.

So with both send and recv at zero, when the first data is written it goes to slot 1 and send is incremented to 1; when the 2nd data is written it goes to slot 2 and send is incremented to 2.  If you now read from the queue, in recv you use the send counter to extract the data instead of using recv + 1.  Hence the queue fails.

A more logical arrangement might be as follows with the counters renamed in
and out (naming them the same as the access functions is confusing):

in indicates the next 'slot' to be written by send (queue not empty).
out indicates the 'slot' containing the next data to be read by recv (queue not empty).
if in == out the queue is empty.

So with both send and recv at zero, when the first data is sent, it goes into slot 0 (to which in and out already point) and in is incremented to 1.  The first read now reads from out at 0 - which is correct.

On thread safety, it is very difficult to see/analyse such things.  You would be
better to assume that it isn't (it certainly wouldn't be if there were more
than 2 threads) and use a mutex.  As your wait loops need to be rewritten
(they just waste CPU cycles needlessly) and you are using Posix threads, use a
Posix mutex and a "condition variable" to synchronise.

Here's an example, but there are many more on the web: http://www.ibm.com/developerworks/library/l-posix3/

Some minor coding points:

Add const to pointer parameters that do not change.
Return a value from create
Don't cast the return from malloc.  Casting is necessary in C++ not C
(where void* can be assigned to any pointer).  In C, adding a cast can cause
problems if you don't have the header for malloc included, as the compiler
will assume that malloc returns an int.  If int and pointer have
different sizes this is a problem.
null is not really needed.  You can use either 0 or NULL.
the _t type suffix is apparently reserved by Posix.


By moving this question from StackOverflow to here, usr's sensible remarks were lost. I restore them here as community wiki:

No, this is fine and recommended. You'll find a limitation of this approach: You cannot use these extension methods in places where they get turned into an expression:

db.Something.Any(x => x.Users.WhereInRole(RoleEnum.Admin))

This does not work because EF does not know the WhereInRole method.

The AsExpandable extension method can help with this. Search the web to find it as a small library.

Using the same approach you should be able to inline constants such as the role ID into the query as well.

Note, that the design of WhereInRole is not really ideal. Normally, you'd write a method bool IsUserInRole(User, int). No need to operate on sequences at all. The only reason this is not possible here is that you need to find a way to marshal the filtering logic into the final expression tree. Shoving the logic into the argument to Where is a hack to do that. This issue/concern is a "dirty secret" of LINQ. It's quite hacky and arbitrary.


Short answer: creating - and garbage collecting - N arrays of size N takes some time, even if operator new[] has been tuned for exceptional performance (as is the case for Java and C#).

int temp[]=new int[arr.length];

Long answer: a detailed treatment of all the coding/performance sins inherent in the code offered for review would fill many pages. However, I'm leaving that for someone else and instead I'll focus only on the algorithmics, in a language-agnostic way.

Throwing needlessly complicated technology at a practice problem can be educational, if only to drive the lesson home that the technology in question is in fact not a good match for the problem and that other solutions require less effort. Hence, if a problem listed under ‘merge sort’ then one ought to also solve it via merge sorting, but the first call should always be the simplest solution that promises to do the job.

In this case, that simplest solution is using a Fenwick tree to count inversions. No fuss, no muss, solution (C#) accepted with 1.19 s combined time for all test files.

const int MAX_VALUE = 1000000;

for (int t = int.Parse(Console.ReadLine().Trim()); t-- > 0; )
{
    int n = int.Parse(Console.ReadLine().Trim());
    var a = new int[n];

    for (int i = 0; i < n; ++i)
        a[i] = int.Parse(Console.ReadLine().Trim());

    var fenwick = new int[1 + MAX_VALUE];
    var result = new int[n];

    for (int i = n - 1; i >= 0; --i)
    {
        int a_i = a[i], inversions = 0;

        for (int j = a_i; j > 0; j -= j & -j)
            inversions += fenwick[j];

        for (int j = a_i; j <= MAX_VALUE; j += j & -j)
            ++fenwick[j];

        result[i] = inversions;
    }

    Console.WriteLine(string.Join(" ", result));
}

Compare this to the reams of code necessary for the merge sorting approach.

According to the problem constraints, values can go ten times as high as indices (limit 10^6 instead of 10^5). This makes the Fenwick ten times as big as the biggest input array, increasing the average path lengths for the Fenwicking from not quite 9.5 to not quite 11.5. However, for small ranges such as these this inefficiency is negligible - the code is more than fast enough already.

For details on Fenwick trees see the Wikipedia article on Fenwicks and the related practice section on HackerEarth (which includes a tutorial; it's in the Data Structures section which you're supposed to work through before starting with Algorithms). As regards determining the average iteration counts for the Fenwick loops, I'd recommend doing a bit of Fenwicking with pen and paper (for a Fenwick of size 2^k it's k / 2 + 1).

As regards merge sorting: unlike Fenwicks, merge sorting does not give a flying meow about what the actual ranges of the input values are - all it does with the inputs is compare them. This makes the algorithm especially attractive when the value range diverges wildly from the value count. For example, Fenwicking 100000 longs would require sorting the inputs in order to ‘compress’ them to the range 1 to 100000, which requires O(N log N) of extra effort.

Merge sorting requires no such preprocessing, but since it destroys the original order of the values it requires extra effort for correlating the inversion counts thus found to the original inputs (e.g. the array copy[] in the original code). Also, it makes the code quite a bit more complicated than that using a Fenwick tree, and it would get hugely more complicated if the input values weren't guaranteed to be unique whereas the Fenwick couldn't care less about uniqueness.

Coding a top-down merge sort with recursive function calls - as opposed an iterative bottom-up version with nested loops - makes it more difficult to control certain aspects (e.g. optimal splitting instead of simple halving) and it makes it even more difficult to make sorted ranges end up precisely where they're needed, instead of resorting to redundant copying of values.

However, the recursive version has somewhat better cache locality and in any case it is more than fast enough for this problem, regardless of the redundant copying. In my benchmarks it took little more than twice as long as the simpler Fenwick and was only marginally slower than an iterative version (124 ms for 10^6 values recursive vs 110 ms iterative and 44 ms Fenwick). In a coding challenge it might pay to keep the differences in mind, but not for this simple practice problem.

Hence the only algorithmic fix required here is using a pre-allocated temp array large enough to hold the largest input. That's all.


Using methods and constructors to construct a basic calculator

This can be simplified:

double exp(double op1, double op2){
double result = 1;
while (op2 > 0){
    result = result * op1;
    op2--;
}

return result;
}

You should be using the Math.pow() method:

double exp(double op1, double op2){
    return Math.pow(op1, op2);
}

Also, you should use proper indentation to help you read and understand your code better, which will help prevent bugs.

This doesn't do anything:

simpleCalc(){

}

It is best to remove code like this to make your project easier to understand and maintain.


Computed properties vs methods with shape classes

Using a superclass

ShapeSC shouldn't be a superclass,
because it provides no useful implementation.
A shape with 0 area and perimeter doesn't make any sense.
Since there are no abstract classes in Swift,
ShapeSC cannot enforce sub-classes to override its methods.
So it's an outright dangerous approach,
as implementors may forget to replace the useless method with meaningful ones.

Btw, the π variable didn't belong in ShapeSC,
as it's only useful for Circle,
not by any other class in the hierarchy.

On the other hand,
it would have made sense to make Square extend Rectangle,
and inherit much of its implementation.

One small final note, I would write Rectangle's calcPerimeter method as:

   override func calcPerimeter() -> Double {
      return 2 * (width + height)
   }

Using a protocol

If you notice,
writing it using a protocol automatically cleaned up some odd elements of the superclass variant:

π is naturally defined in Circle, not somewhere else needlessly
No more 0-area 0-perimeter objects, by design

Even the code is shorter.
There are no obvious downsides either, which is in stark contrast with the superclass variant.

Using a mixed hierarchy

Consider a mixed hierarchy, using protocols and inheritance where they make sense.
For example Shape should clearly be a protocol,
but Rectangle can be a class that specialized cases like Square can inherit from.
As you explore the shape universe,
there might be other cases in the hierarchy where a protocol might make sense.


Working with Classes (inheriting), @ properties and Initialization

This is my first review so bear that in mind when you are reading it.

The first thing I see is that in the initialization, you should not use the automatic setters and getters for properties.  The reason for this is that the object may not be completely initialized, and thus may fail.  So instead of doing:

self.a1 = x;
self.a2 = s;
self.a3 = y;

access the properties directly like so:

_a1 = x;
_a2 = s;
_a3 = y;

Otherwise, your init pattern is good, and bonus points for having a default -(id)init that calls your designated initializer.

For the names of all of these, I would make sure to always use a more descriptive name.  It is probably okay in such a simple example to use a1, x, y, etc, but for anything more complicated, use names that describe in more detail exactly what the variable is.

In the description method it looks like you are calling the int values with %d.  I can't think of a reason not to use %i, but maybe I am wrong here.

One last thing, in the interface the spacing inside the declaration of -(id)initWithEtc is loose.  It looks correct in the implementation though.


A class for simple and efficient operations on boost::unordered_set

Fix compiler errors

Your set_difference function does not compile. You have declared it returning bool, but then return differenceSet; in the function body. This is a type mismatch: your function should return a boost::unordered_set.

Reinventing the wheel

boost::unordered_set already supports operator== for equality comparison. You don't need to implement it yourself -- your are_equal() function is unnecessary.

Additionally, your set_union can be simplified. You can replace your foreach-loop:

BOOST_FOREACH(const Type &element, setA){
            unionSet.insert(element);
        }

with using the two-iterator overload of insert():

unionSet.insert(setA.begin(), setA.end());

This should be no less efficient than what you have already written, and is slightly more readable.

Remove irrelevant comments

set_difference() contains this comment: //is size are not equal, sets are not equal. This has no relevance to what the function actually does. This, combined with the type error listed above, leads me to believe that this is a copy-paste error. When you do that, make sure things like this don't slip through.

Boolean comparison

You don't need to explicitly compare Boolean conditions against false:

if(set_hasElement(setB,element) == false)

Can be more succinctly stated:

if(!set_hasElement(setB,element))

Naming

This is a minor nitpick, but set_hasElement combines underscore_separated and CamelCase capitalization conventions. I would rename it to set_contains() for name consistency with the rest of your functions.

Namespaces

Creating a class with only public static functions is very Java-esque. C++ allows namespaces, which are a way of organizing functions and classes. Your set functions might be better as free functions placed in a namespace SetUtilities instead of a class.


Alternate threads to print even and odd numbers

I have two comments of the tweaking kind:

1) any variable that is shared between threads has to be volatile. this is true even for static variables that have one value throughout the JVM (actually it is per class loader but this is irrelevant here). The reason for that is that threads can locally cache the value of variables.  volatile variables force the thread to read the global value each time.

You might also want to take a look at AtomicInteger which is an int that is guaranteed to be incremented synchronously and that has the same value for all running threads.

2) while synchronized will work, Java concurrency package has several Lock mechanisms that allow for better control over the synchronization process.  of relevancy here are ReentrantLock, ReadWriteLock.


Hard coding

Is too easy...

The first problem I see is that the sorting has the event type hard coded into the function.

I feel that hard coding any type of data into code is bad practice. At minimum if hard coding values is unavoidable the values should be defined as a constant and placed in a common location in the source file.

The problem with hard coding is the inevitable need to change or add to the hard coded items. This is a difficult process when the values are scattered in the code, and usually not easy to find as they are not unique.

For a simple fix I would add

const eventTypes = { a : "a", b : "b" };  // at the top of the source file
                               // or in a common file, and as close
                               // to the required scope as possible
                               // as to not be in global

Then in the code

if(event.type === eventTypes.a){  ...
if(event.type === eventTypes.b){  ...

Thus if you want to change you do so where you define the const and if you need to change the code you can us refactor tools to locate the unique types in your code base.

Using data given.

Better yet is to avoid the constants all together and use the data in the array items. You can compare strings with "stringA" < "stringB" is true. Javascript uses the strings char codes to evaluate the condition, that means that "stringa" < "stringB" is false as lowercase characters have a higher character code than capitals.

So assuming that event types are all lowercase you can sort the events with a standard sort function.

Thus the steps would be

Sort all events by time.
Reduce the events array to event type, adding an array of times to each type.
Sort the reduced events by type.
Empty events array and reconstruct events using the following method.
From the lowest time search the reduced array for matching times. Add to the events array matching time and associated type. Removing time from type if more than one time, and or remove type if only one time for type, until reduced array is empty.

Testing

The data set you have given, is very limited and thus the problem is a little ambiguous. To ensure that the function works you should provide data with at least every combination of possible data combinations (Not all combinations "abc" is the same as "gef" but different than "aac" and "abca" ) that will affect the ordered result.

Sometimes testing can not test all possible input possibilities as the number of tests is so large to be impractical. The best way to deal with such is to create randomised data and do a statistical test. You can not prove the function will not fail, you can prove it will.

in other words...

You can then say your function has only a small statistical chance of failure if you don't get a fail. If you get any fail then your function is known to fail and should be fixed.

I used a random test (as I am can't be bothered doing a complete test, and i Imagine it most matches the expected input) to test the function. Your function failed on the very first random test with a typeError (I did not examine the details)

The other answer given by GerritO also failed incorrectly ordering most test inputs.

An example of test data that fails

const events = [
  { type: 'a', timestamp: 1 },
  { type: 'a', timestamp: 4 },
  { type: 'a', timestamp: 3 },
  { type: 'c', timestamp: 1 },
  { type: 'b', timestamp: 1 },
  { type: 'a', timestamp: 2 },
  { type: 'a', timestamp: 2 },
  { type: 'c', timestamp: 2 },
  { type: 'b', timestamp: 2 },
  { type: 'b', timestamp: 2 },
];

//or
  [{ type: 'a', timestamp: 1 },
  { type: 'g', timestamp: 4 },
  { type: 'a', timestamp: 3 },
  { type: 'b', timestamp: 2 },]

A more robust function.

The rewrite has made a few assumptions, and has been tested on a huge set of random inputs without failing (no fail in over 10 million random input tests). That does not mean it does what you want, it does what I guessed you want. Order events by time, in same time groups, order events in alphabetical groups

Rather than modify the existing array I have created a new array to hold the results.

// test data example
const events = [
  { type: 'a', timestamp: 1 },
  { type: 'g', timestamp: 4 },
  { type: 'a', timestamp: 3 },
  { type: 'h', timestamp: 5 },
  { type: 'c', timestamp: 1 },
  { type: 'b', timestamp: 1 },
  { type: 'a', timestamp: 2 },
  { type: 'a', timestamp: 2 },
  { type: 'c', timestamp: 2 },
  { type: 'b', timestamp: 2 },
  { type: 'g', timestamp: 3 },
  { type: 'b', timestamp: 2 },
  { type: 'e', timestamp: 3 },
  { type: 'f', timestamp: 1 },
  { type: 'f', timestamp: 3 },
  { type: 'h', timestamp: 5 },
  { type: 'f', timestamp: 3 },
  { type: 'f', timestamp: 3 },
];

/* Please note this uses compact style. Single block statements are followed
   by `{ code }` when under 80 chars (tab 2). No `;` is added to comply with
   JSLint rule Semicoloans must be followed by newline. */

function reorderEvents(events){
    /* global to this function variables */
    // timeClear is flag to indicate that there are no events at the current event time
    // eventTime is the current event time to add to result
    var timeClear, eventTime, eIdx = 0; // index into ev arrray

    /* Functions global to this function */
    const typeSort = (a, b) => a.type < b.type ? -1 : a.type > b.type ? 1 : 0;
    const getEvent = () => {                        // gets event matching eventTime from reduced events
        if (ev[eIdx].times[0] === eventTime){       // does the event match the event time
            timeClear = false;                      // flag that it is unknown if there are more times at eventTime
            if (ev[eIdx].times.length === 1) {      // is this the only time for event
                const event = ev.splice(eIdx,1)[0]; // remove from array
                return { type : event.type, timestamp : event.times[0] }; // return the event
            }
            return { type : ev[eIdx].type, timestamp : ev[eIdx++].times.shift() }; // remove the time
        } else { eIdx ++ } // skip the event as not at the event time
    }

    const orderedEvents = [];   // Will hold the results and is returned by this function
    const reduced = new Map();  // holds events type as key and array of event times per key

    // We dont want to mess with the original array and as sorts are in place we need to copy the array
    events = [...events];
    events.sort((a,b) => a.timestamp - b.timestamp );  // Order events by time

    // reduce events to type
    events.forEach((event) => {
        const existing = reduced.get(event.type);
        if (existing === undefined) {
            reduced.set( event.type, { type : event.type, times : [event.timestamp] });
        } else { existing.times.push(event.timestamp) }
    });

    // get the reduced events from the Map and sort by type
    const ev = [...reduced.values()].sort(typeSort);
    timeClear = true;    // first pass the abstract previouse pass is clear

    // remove all events in order of time
    while (ev.length > 0) {
        if (eIdx === 0) { // if this the first item
            if (timeClear) { eventTime = ev[0].times[0] }  // get next time
            else { timeClear = true }  // clear flag and do another pass
        }
        const event = getEvent();
        if (event !== undefined) { orderedEvents.push(event) }
        eIdx = eIdx === ev.length ? 0 : eIdx ; // goto start when past end
    }
    return orderedEvents;
}
// To avoid console log function
function log(data) {
    const d = document.createElement("div");
    d.textContent = data.toString();
    document.body.appendChild(d);
}
const ordered = reorderEvents(events);
ordered.forEach(i => log(i.type + " : " + i.timestamp));


It doesn't seem that the pq library has a query builder or a specific type. So building a query in an idiomatic and readable way should be done as you would do for a normal string, and that is using the text/template package. This will allow you to get rid of many code smells:

the line containing your query is long and not easily readable, maybe skip more lines
you can write the skeleton to your query once, instead of using successive appends — this is also more efficient if you have many services
the call to strings.TrimSuffix can be avoided using a simple condition in your template
you can replace (select company.id from company) directly by its value, that you previously computed in your Go code
and you can get rid of the []interface{} variable that you pass to Prepare & Exec, just do all the substitution logic in the go code.

Various unrelated things:

Don't write var int i = 3, write simply i := 3.
I'm not sure why Company and Service have to be exported, since you seem to only use them to build a query.
When doing successive += operations on a string, consider using a buffer instead, see this question. (But here, it's moot, since using a template is more idiomatic.)


MemoryError in Python while combining multiple JSON files and outputting as single CSV

You're storing lots of results in lists, which could be streamed instead. Fortunately, using generators, you can make this ‘streaming’ relatively easy without changing too much of the structure of your code. Essentially, put each ‘step’ into a function, and then rather than appending to a list, yield each value. Then you’d have something that might look like this:

def load_json():
    for file in open_files:
        for line in file:
            # only keep tweets and not the empty lines
            if line.rstrip():
                try:
                    datum = json.loads(line)
                except:
                    pass
                else:
                    yield datum

Then you could replace

for tweet in tweets:

with

for tweet in load_json():

But this will still store the IDs into ids, texts into texts, etc. You could use a bunch of generators and zip them together with itertools.izip, but the better solution would be to extract the columns from the tweet when writing each line. Then (omitting the UTF-8 encoding piece, which you'd want to rewrite to work on dictionaries) you’d have

for tweet in load_json():
    csv.writerow((tweet['id'], tweet['text'], ...))

Lastly, since this is Code Review, you might consider putting all the keys you want to pull out into a list:

columns = ['id', 'text', ...]

Then your row-writing code can be simplified to

csv.writerow([tweet[key] for key in columns])

Rewriting it this way, you can then UTF-8 encode rather easily (using a helper function):

def encode_if_possible(value, codec):
    if hasattr(value, 'encode'):
        return value.encode(codec)
    else:
        return value

csv.writerow([encode_if_possible(tweet[key], 'utf-8') for key in columns])


Some ideas:

I'd try encapsulating the position and mask parameters to one parameter. Maybe a struct would be fine for this. It is easy to mix up the parameters of ret, for example, somebody could call it accidentally with

`ret(output, secondnum_pos, firstnum_mask)`

or with

`ret(output, firstnum_mask, firstnum_pos)`.

(Note the parameter order.)
Consider writing tests which store the i, j, k values in different order. Currently they do not detect if storing at the firstnum_pos overrides the second or the third values.
Consider making copies of i, j and k for the assert calls before you call the marcos. If a macro accidentally changes values of i, j or k the assert will not detect it.
A unit testing framework would be better for the testing: Unit Testing C Code


Your method reads an object from a JSON file which is embedded in the application bundle, and aborts with a runtime error if that fails for any reason. That is fine: Bad embedded data are a programming error and should be detected early.
The return type of the parse() method should not be an optional because it never returns nil.
The custom error type is used to pass errors from the helper methods to the main method. That has two disadvantages:

It hides (possible more informative) errors thrown from other methods, e.g. the JSON decoder method.

The messages printed with fatalError() show only the error type and an integer, for example
Fatal error: The operation couldn’t be completed. (MyApp.JSONError error 0.)

The second issue can be improved (see for example How to provide a localized description with an Error type in Swift? on Stack OverFlow) but I would go another route and pass on existing errors instead, where possible:
In parseJson() you can pass the error which the JSON decoder already throws, instead of shadowing it by a custom error:
private func parseJson<T: Decodable>(data: Data, type: T.Type) throws -> T {
    try JSONDecoder().decode(type.self, from: data)
}

And in getJsonContents() you can use the (throwing) Data(contentsOf: url) method to read the data, that is also simpler than reading into a string and then converting the string to data.
It remains to handle an error in Bundle.main.url(forResource:withExtension:), that method does not throw an error but returns an optional.
Without the do-catching in the helper methods everything fits neatly into the main method:
func parse<T: Decodable>(type: T.Type) -> T {
    guard let url = Bundle.main.url(forResource: self.fileName, withExtension: "json") else {
        fatalError("file not found")
    }
    do {
        let data = try Data(contentsOf: url)
        return try JSONDecoder().decode(type.self, from: data)
    } catch {
        fatalError("\(error.localizedDescription)")
    }
}

You many also want to print the full error and not its localizedDescription because that can provide more information (and the string is not presented to the user of your program but only for diagnostic purposes).
Finally, I wonder if fileName should really be an instance variable. If it is only used in the parse() method and nowhere else then you can make it a parameter of a static  method:
struct JSONService {
    static func parse<T: Decodable>(type: T.Type, from fileName: String) -> T {
        guard let url = Bundle.main.url(forResource: fileName, withExtension: "json") else {
            fatalError("file not found")
        }
        do {
            let data = try Data(contentsOf: url)
            return try JSONDecoder().decode(type.self, from: data)
        } catch {
            fatalError("\(error)")
        }
    }
}

which would be called as
let value = JSONService.parse(type: MyType.self, from: "filename")

Embedding it into a struct JSONService is still useful as it provides a “name space“ for its static methods. If there are only static methods then you can embed them in an enum JSONService instead, because no instance of that type needs to be created (thanks to @Shadowrun for reminding me about that).


Refactor/Review JS function which moves a banner on window resize

Ok, assuming:

You didn't use media queries for cross-browser reasons
This function is already bound to a resize event, since you didn't include what triggers the function call
Assuming that this is the window object, judging from the way you call it vp as in viewport and getting its width.

Then:

function updateReadyGoBG(){

        //you can actually merge declaration and assignment
    var vpWidth   = jQuery(this).width(),
        //cache the ready_go_bg jQuery object to avoid requerying
        readyGoBg =  jQuery('.ready_go_bg'),
        position  = 0,
        difference;

    if(vpWidth > 980 && vpWidth < 1067){

        //you could use position instead of getting the CSS left
        //to avoid getting a string, and chopping off the "px" part
        position = readyGoBg.position().left;

        difference = (position - (600 - (vpWidth - position) ) ) + 100;

        //sadly, position is just a "getter".
        //you could use .offset(value) but calculating relative
        //to your offset parent would be too much work
        //we use .css(prop,value) to set the left value
        //if unit wasn't specified, jQuery assumes it's in pixels
        readyGoBg.css('left', difference);
    }
}

function updateReadyGoBG() {
    var vpWidth = jQuery(this).width(),
        readyGoBg = jQuery('.ready_go_bg'),
        position = 0,
        difference;
    if (vpWidth > 980 && vpWidth < 1067) {
        position = readyGoBg.position().left;
        difference = (position - (600 - (vpWidth - position))) + 100;
        readyGoBg.css('left', difference);
    }
}

General Advice:

Never forget ; at every line. You may run into issues during minification if you forget them
Though personal preference, but it's cleaner to use ' instead of ".
Unless totally necessary, I'd avoid absolute positioning. Let the layout dictate positions.


Perhaps you could wrap it all in a function:

function pagination($this,$viewList,$keywordQuery)
{
    $this->paginate    = array(
        'fields'    =>  array(
                        'DISTINCT Contact.contact_id',
                        'Contact.first_name',
                        'Contact.last_name',
                        'Contact.email',
                        'Contact.created',
                        'ContactGroup.name',
                      ),
        'conditions' => array(
                        $this->conditions,
                        'ContactsContactGroup.contact_group_id'=>$viewList,
                        isset($keywordQuery)?$keywordQuery:"",
                      ),
        'limit'      => 5,
         'group'     => array('Contact.contact_id')
                      );

   return $this->paginate('ContactsContactGroup');

}

if(something())
{
    //something
    $data=pagination($this,$viewList,$keywordQuery);
}
else
{
    //other
    $data=pagination($that,$viewList,$keywordQuery);
}

etc..


Use capital letters with underscores for constants https://pep8.org/#constants
There is no need to wrap alphabet string into parentheses:

ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_.;#@"
LENGTH = 6

Expression str(pw) does nothing so you can remove it. You probably meant pw = str(pw) but it is redundant since pw already is str
You do not need array variable at all, just iterate over input file line by line. Also, unpacking is more readable:

    for line in ins:
        user, password, *rest = line.split(":")
        users.append(user)
        passwd.append(password)

Since you ignore passwords "*" and "!" it is better to filter them out when reading from file.
Since ins is not used after generating users and passwd lists you do not need to place rest of code inside with block. Actually, the first block may look like:

#getting passwords and username from shadow file
with open("shadow_test", "r") as ins:
    users = []
    passwd = []
    for line in ins:
        user, password, *rest = line.split(":")
        if password not in ('*', '!'):
            users.append(user)
            passwd.append(password)

Why do you need for _ in range(12) loop? Just to make the program 12 times slower? Remove it.
Do not use names of built-in funciton names for variables, like list. BTW, why do you need it at all? Just iterate over all possible words and look for their hash in passwd:

passwords = (''.join(word) for word in itertools.product(ALPHABET, repeat=LENGTH))
for pswd in passwords:
    # calculate hash of pswd and if it is equal to one in passwd print it

When you compare generated hash with elements of passwd you do not need to iterate over all usernames and print them all! Actually it is better to make "password hash" -> "username" dictionary so you can check if generatedpassword is one of given password hashes faster (because checking that dict has a key generally is faster than checking each element of array):

with open("shadow_test", "r") as ins:
    data = dict()
    for line in ins:
        username, password, *rest = line.split(":")
        if password not in ('*', '!'):
            data[password] = username

password_hash = md5hash("qwerty")  # assume it is a function for calculating md5
if passwod_hash in data:
    print("qwerty is password of", data[password_hash])

It is probably better to remove "$1$" from stored records rather than add it to each calculated hash:

if password not in ('*', '!'):
    assert password.startswith("$1$"), "Expect password records to begin with $1$"
    data[password[3:]] = username  # remove $1$

So the whole solution may look like:

import hashlib
import itertools

def md5hash(char_sequence):
    string = ''.join(char_sequence)
    hash_object = hashlib.md5(string.encode())
    return hash_object.hexdigest()

# possible characters in user password
ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_.;#@"
# password length
LENGTH = 6

# getting passwords and username from shadow file
with open("shadow_test", "r") as ins:
    data = dict()  # hash -> username mapping from shadow file
    for line in ins:
        username, password, *rest = line.split(":")
        if password not in ('*', '!'):
            data[password[3:]] = username  # remove $1$

# bruteforce
for word in itertools.product(ALPHABET, repeat=LENGTH):
    generated_hash = md5hash(word)
    if generated_hash in data:
        print('The password of user', data[generated_hash], 'is:', word)
```


Check existence of a row then update a column

Obviously, you already know about SQL injection. So let's forget about that. Ideally, please do defend against it, it's easy enough that it's not worth doing it any other way. Code that is not public facing now, might be next week.

Some other things:

You use fetchall instead of fetchone. fetchall has to load all rows into memory (I assume), which is pretty expensive. Don't use it.

Also, you use SELECT *, which needs to load all columns (of the relevant rows) into memory. Again, expensive.

def check_word(self, word_name):
    self.c.execute('SELECT {c2n} FROM {tn} WHERE {c1n} = """{wn}"""'.format(tn=self.table1, c2n=self.column2, c1n=self.column1, word=word_name))
    data = self.c.fetchone()
    if data is not None:
        new_freq = data[0] + 1
        self.c.execute(
            'UPDATE {tn} SET {c2n}={en} WHERE {c1n}="""{word}"""'.format(tn=self.table1, c2n=self.column2,
                                                                     en=new_freq, c1n=self.column1,
                                                                     word=word_name))
        return True
    return False

Also, there is a bit of a trouble with race-conditions here, but that's probably easily solvable using transactions and locking. Or, better, use 1 query (which is also faster!)

def check_word(self, word_name):
    query = 'UPDATE {table_name} SET {counter} = {counter} + 1 WHERE {word_column} = ?'.format(
        table_name=self.table1,
        counter=self.column2,
        word_column=self.column1,
    )
    self.c.execute(query, word_name)
    return self.c.rowcount > 0

(Here, I use the rowcount attribute of a cursor which returns the number of rows changed in the last query: https://docs.python.org/2/library/sqlite3.html#sqlite3.Cursor.rowcount).

I tried to use more sensible names for the columns, and also used string-interpolation for the values that are hopefully not under user control (and can't be done using parametrized queries anyhow), while using paramatrisation for the word_name which is more likely to change.


An implementation of maximum subarray finding algorithm in STL style

Do not rely on the client code to #include necessary headers. The client has no idea which headers your file requires. Spell them out explicity:

#include <iterator>
#include <tuple>

Are you sure you are using c++11? I am getting

error: 'auto' return without trailing return type; deduced return types
are a C++14 extension

In general, naked auto returns in an interface is a dubious idea. Again, think of the client. The client should not analyze your template to deduce what it actually returns. It is OK to have them in the helper functions not exposed to the client.
It took me a while to figure out why your code works correctly. The side effect of ++ in

For right = ++begin;

is very easy to miss.


Writing a class to hold Arduino Properties for an Arduino I2C Debugger

Here is some feedback I have. I haven't had a chance to work with Arduino much, but there are some things that stand out to me:

 # Nothing to glaring in your constructor, but some tidbits:
 # I might add some defaults.
 # I also noticed you have a lot of items in your constructor.
 # Maybe **kwargs is warranted.

def __init__(self, tree_item, port=8080, identifier):

or

def __init__(self, **kwargs)

    # the number of arguments is borderline imho. I usually find if I
    # have too large a number (subjective), there is opportunity to
    # break out the code into more classes.
    self.__i2c = ArduinoI2C()
    self.__i2c.setPort(port)
    self.__i2c.connectPort()
    self.__id = None
    self.__i2c_version = None
    self.__switch_version = None
    self.__tree_item = tree_item
    self.__address_list = []
    self.__port = port
    self.__identifier = identifier

# Typically methods indicate some sort of action. i.e. get_id, show_id.
# specifying a noun is usually grounds for a class/instance variable.
# I would consider renaming your method to "def get_id(self):"
@property
def id(self):
    if self.__id is None:
        try:
            self.__id = self.__i2c.getID()
        except IOError:
        # It may be good to add some logging.
        # python logging module is great.
            self.__id = "NO CONNECTION"
    return self.__id

# ditto method name
@property
def i2c_version(self):
    if self.__i2c_version is None:
        try:
            self.__i2c_version = self.__i2c.i2cVersion()
        except IOError:
        # ditton on the logging.
            self.__i2c_version = "NO CONNECTION"
    return self.__i2c_version

# ditto method name
@property
def switch_version(self):
    if self.__switch_version is None:
        try:
            self.__switch_version = self.__i2c.switchVersion()
        except IOError:
            self.__switch_version = "NO CONNECTION"
    return self.__switch_version

# ditto method name
@property
def tree_item(self):
    return self.__tree_item

# ditto method name
@tree_item.setter
def tree_item(self, item):
    if type(item) is not wx.TreeItemId:
        return
    self.__tree_item = item

# ditto method name
@property
def address_list(self):
    return self.__address_list

# ditto method name
@address_list.setter
def address_list(self, addr_list):
    if type(addr_list) is not list:
        return
    self.__address_list = addr_list

# ditto method name
@property
def port(self):
    return self.__port

# ditto method name
@port.setter
def port(self, port):
    if port[:3] != "COM":
        return
    self.__port = port

# ditto method name
@property
def identifier(self):
    return self.__identifier

# ditto method name
@identifier.setter
def identifier(self, letter):
    if type(letter) is not str:
        return
    if letter[-1] != ':':
        letter += ':'
    self.__identifier = letter

# ditto, and its not idiomatic to use camelCase in a method name.
#   def run_serial_command(self, command)
def serialCommand(self, command):
    """
    Wrapper for ArduinoI2C serialCommand function
    """
    return self.__i2c.serialCommand(command)

# this method name is ok
def close(self):
    self.__i2c.close()

# this one two.. ditch the camelCase for snake_case connect_port
def connectPort(self):
    self.__i2c.connectPort()

It looks like there might be some opportunity for grouping your commands into separate classes, however not sure if you have enough per group yet.

i.e.

class ArduinoVersions(ARCArduino):

# this might be to ambiguous, but just trying to give the general idea.
class ArduinoProperties(ArcaArduino):

I have a feeling your command set will grow, so breaking this out may provide better organization in the future.


Reorganizing a PHP array structure (arrays within arrays)

Why

You're replacing the indexed item for the date when you declare a new array in the line:

$mainarr[$array[$i][1]] = array( $array[$i][0]=> array('downloads'=> 666, 'col'=>$array[$i][2]) );

See it as $array[$index] = array(...) -- running it again over the same index would replace the value at that index.

Quick Fix

You could simply replace that line with (considering that there'll not be more than one line for a given country, for the same date, as in: no two DE for 2015-06-08):

if (!isset($mainarr[$array[$i][1]])) { $mainarr[$array[$i][1]] = array(); }
$mainarr[$array[$i][1]][$array[$i][0]] = array('downloads'=> 666, 'col'=>$array[$i][2]);

Note that $array[$i][0] (aka the country) moved to the left site of =, and the outer array on the right side of it was removed.

How would I do

I refactored the code to be more legible and easier to understand, and also use better practices IMHO:

function get_cols_to_array_by_date($array) {
    // set the name of the variable to a more meaningful one
    $result = array();

    foreach ($array as $i => $data) {
        // shortcuts to prevent having to remember which index they are (you could change them for constants)
        $country = $data[0];
        $date = $data[1];
        $col = $data[2];

        $download = 123; // don't know where 'download' value comes from, put it here

        // you need to check if the date index already exists
        // if not, create the empty array for the date
        if (!isset($result[$date])) {
            $result[$date] = array();
        }

        // considering that country will NOT repeat for a given date
        $result[$date][$country] = array(
            'column' => $col,
            'download' => $download,
        );
    }

    return $result;
}


Creating a simple unit of work with Entity Framework and no repository

I can be very short about this:

Single responsibility: a controller shouldn't also have Unit of Work responsibilities. The context itself is the perfect Unit of Work.
You don't always need SaveChanges
Use dependency injection.

I like to see controllers as light-weight doorways to web-independent service methods. The services have their own DbContext and execute SaveChanges where necessary and, thus, can be used in other applications than just MVC/Web API applications. Controllers receive services by dependency injection.


Laravel - Repetitive code in store and update functions

No need to get all data from database. Instead, only update those rows that need to be updated. Only if needed, you should work with database, avoid otherwise. Database I/O is biggest speed consumer in web applications and generally in PHP applications [when used]. https://laravel.com/docs/master/eloquent#updates

Check this one for store method, should work way faster:

public function store(Request $request)
{
    $user = Auth::user();

    $validatedData = $request->validate([
        'street' => ['required', 'string'],
        'number' => ['required', 'string'],
        'city' => ['required', 'string'],
        'state' => ['required', 'string'],
        'postal_code' => ['required', 'string'],
        'country' => ['required', 'string'],
        'phone' => ['required', 'string']
    ]);

    $billing = $request->is_billing ?? 0;
    if ($billing) {
        Address::where(['is_billing' => 1])->update(['is_billing' => 0]);
    }

    $address = Address::create([
        'user_id' => $user->id,
        'token' => Str::random(32),
        'street_name' => $request->street,
        'house_number' => $request->number,
        'postal_code' => $request->postal_code,
        'state' => $request->state,
        'city' => $request->city,
        'country_id' => $request->country,
        'phone' => $request->phone,
        'is_billing' => $billing
    ]);

    return redirect('/dashboard/user/' . $user->user_token . '/addresses');
}

Next, insted line $user = Auth::user(), you can work with policies ( https://laravel.com/docs/master/authorization ). In docs you can see PostPolicy how's been created and yours should be named AddressPolicy.
And also, you should move validation to request file created with let's say

php artisan make:request AddressStoreRequest

Again, in docs you will find how to set code there ( https://laravel.com/docs/master/validation#creating-form-requests ).
That is what you can do to release controller method of code and set those code blocks in their respective classes. Although your code (way I wrote it above avoiding unnecessary DB calls) will work the same even if you don't make separate classes for form validation or for authorization.

Use this code and make similar for update method.


I would start with the following improvements:

better naming - for instance, r is not a good variable name. Remember that code is much more often read than written
avoid hardcoding constants - define them as proper Python constants (these are not really constants, but more like a guideline)
you can use next() built-in function instead of a list comprehension and then getting the first filtered item
you can unpack the credentials tuple into the HTTPBasicAuth arguments
avoid having a bare except clause - catch more specific exceptions if needed

Improved code:

import requests
from requests.auth import HTTPBasicAuth

REFERER = 'http://natas5.natas.labs.overthewire.org/'
KEYWORD = 'natas5'

def exploit(host, credentials):
    """TODO: docstring here"""
    try:
        response = requests.get(host,
                                auth=HTTPBasicAuth(*credentials),
                                headers={'referer': REFERER})

        response_lines = response.content.decode('ascii').split('\n')
        return next((line for line in response_lines if KEYWORD in line), 'Keyword not found')
    except requests.RequestException as e:
        print(e)

def main():
    host = 'http://natas4.natas.labs.overthewire.org'
    credentials = ('natas4', 'Z9tkRkWmpt9Qr7XrR5jWRkgOU901swEZ')
    print(exploit(host, credentials))

if __name__ == '__main__':
    main()


Seeking improved Objective-C permutation algorithm

Before I comment on performance, I want to comment on style and naming and such.

First and foremost, let's not use single letters for variables.  They're meaningless.  It's hard to follow what's happening in your code when it's just a handful of letters.  Longer variable names has ZERO impact on the runtime performance of your code, but makes a massive difference in the readability and maintainability of your code.

But the thing is, we don't even need the p or l variables.  There's an existing Foundation struct design for EXACTLY this purposes.  It's called NSRange, which consists of two components, a location (what you're calling p) and a length (what you're calling l).

So, let's change the method name to:

- (void)permute:(NSMutableArray *)word range:(NSRange)range;

Now let's fix the internals of the method.  As a note, the following doesn't change any of the logic.  It just fixes up the spacing and naming to make the method more readable:

- (void)permute:(NSMutableArray *)word range:(NSRange)range {
    if (range.location == range.length) {
        [self.allPermutations addObject:[word componentsJoinedByString:@""]];
    } else {
        for (int i = range.location; i < range.length; ++i) {
            NSString *currentWord = word[range.location];
            word[range.location] = word[range.length];
            word[range.length] = currentWord;

            [self permute:word range:NSMakeRange(range.location + 1, range.length)];

            currentWord = word[range.location];
            word[range.location] = word[range.length];
            word[range.length] = currentWord;
        }
    }
}

Now the code is a bit more readable without having sacrificed any readability.

But there are still problems.

First of all, why are we using NSString within the loop?  It doesn't make any sense.  We're not calling any methods on these objects, we're just swapping them around.  Instead of NSString, why not just id?

Second, what happens if p is greater than word.count?  What happens if l + p is greater than word.count?  What happens if p is negative?  What happens if l is negative?  A crash happens--that's what.  If you want this method to find all permutations, then start by having an outer method which takes only an NSMutableArray argument and then calls a method that looks like this but the first call it send an NSRange object with a location of 0 and a length of word.count.

Here's another issue:

    [self permute:word position:p+1 length:l];
    t= word[p];
    word[p] = word[i];
    word[i] = t;

Are these last 3 lines ever executed in a meaningful way?  If you comment every non-brace line after the recursive call out, do the results change?  By the time you get to these three lines, you've already executed

[self.allPermutations addObject:[word componentsJoinedByString:@""]];

As far as I can tell, all those last three lines might be doing is straightening the array back out into its original form... is that the intent here?  That's crazy to have this many executions of code on the way out of the recursive call just to straighten a mutable array out back to its original form, and there's a much better way to do that!

Perhaps I'm misunderstanding the purpose of these three lines, but if I'm understanding this correctly and the only purpose truly is to rewind the array back to it's original position, then let's try this:

- (void)permute:(NSMutableArray *)word range:(NSRange)range {
    static NSMutableArray *copyOfWord;
    if (!copyOfWord) {
        copyOfWord = [word copy];
    }
    if (range.location == range.length) {
        [self.allPermutations addObject:[copyOfWord componentsJoinedByString:@""]];
        copyOfWord = nil; // We're done now.  Set back to `nil` so next call can use it
    } else {
        for (int i = range.location; i < range.length; ++i) {
            NSString *currentWord = copyOfWord[range.location];
            copyOfWord[range.location] = copyOfWord[range.length];
            copyOfWord[range.length] = currentWord;

            [self permute:copyOfWord range:NSMakeRange(range.location + 1, range.length)];
        }
    }
}


You can use Bracket Notation to have custom object key by ['text'+variable].

vm.showComponent = function(componentName)
{
   hideComponents();
   vm['show' + componentName]=true;
}


I see some things that could be improved with this code.

Fix exetime

The exetime word is defined like this:

: exetime  utime 2>r quicksort execute  utime 2r> d- ." dtime " . cr ;

There are a number of problems with that.  First, the formatting is not very good.  I'd prefer to see a stack comment, for example.  Second, this should probably take a parameter so that any word can be timed (this appears to be the intent from run).  Third, that last . should be d. to display the entire delta time rather than just half of it.

: exetime  ( fp -- )
   utime 2>r  execute  utime 2r> d- ." dtime " d. cr
;

Use smaller words

Again using exetime as an example, there are actually two things done by the word as defined.  The first is that it calculates a delta time, and the second is that it prints that time.  I'd make those separate words.

Follow Forth convention

It's common to use prefixes to simplify code.  For example, everywhere ssrt is used, it's followed by @.  For that reason, I'd define and use word like these:

: @ssrt ssrt @ ;
: @size size @ ;
: !size size ! ;

Define and use common idioms

A number of cases in the code there is a sequence like this: size @ . but there is a common idiom for that and it's built in to many Forth implementations.  If it's not, it's easy to define:

: ?  ( a -- )   @ . ;

It would be used like this:  size ?.  Alternatively, one could use the prefix idiom which is associated with a particular value:

: ?size  ( -- )   size @ . ;

Eliminate unused variables

The logs variable is defined but never used.  This needlessly clutters the code.

Simplify control structure

Instead of using begin .. while .. repeat, it's often the case that one can use begin .. until instead and simplify the code.  Using the refactored smaller words as suggested above, here's what run looks like now:

: run ( fp )
    >r
    begin
        copy-array
        array-limits r@ exetime
        ." size " ?size ." dtime " d. cr
    size2x total-size > until
    rdrop
;

These are the refactored words:

: exetime  ( fp -- ) utime 2>r execute utime 2r> d- ;
: copy-array ( -- ) data @ ssrt @ size @ cells move ;
: array-limits ( -- alo ahi ) ssrt @ dup size @ cells + swap ;
: @size ( -- n ) size @ ;
: ?size ( -- ) @size . ;
: size2x ( -- n ) size @ 2 * dup size ! ;

Make sure comments don't lie

The shuffle word starts like this:

: shuffle ( n a -- )

However, that's not correct.  It should instead be:

: shuffle ( n1 n2 a -- )

Use refactoring to improve speed

The code currently contains this:

: median_of_3 ( n0 n1 n2 -- n )
    >r 2dup > if swap then
    r> 2dup > if swap then drop
       2dup < if swap then drop
;

However, in addition to being somewhat opaque, it's not as fast as it could be.  Refactoring into smaller chunks improves both readability and speed:

\ arrange top two stack values to assure n0 <= n1
: lohi ( n0 n1 -- n0 n1 ) 2dup > if swap then ;
\ arrange top three stack values to assure n0 <= n1 <= n2
: 3sort ( n0 n1 n2 -- n0 n1 n2 ) lohi >r lohi r> lohi ;
\ extract median value from top 3 items on stack
: median_of_3 ( n0 n1 n2 -- n1 ) 3sort drop nip ;

Be aware of non-standard extensions

The code uses the non-standard extensions:

 rdrop -rot utime

It is not hard to write replacements for the first two if needed:

: rdrop r> drop ;
: -rot rot rot ;

Since utime is only used in the test code, perhaps it's not as critical.  There is no standard replacement.


Number of anagrams in an array of words (Codewars)

You are making your life too difficult, IMO. Whenever you iterate over all members of a set to see if some element is in it or write list(unique), you are probably doing something wrong.

I would just transform each word into a canonical form (you could choose a frozenset of the Counter items or just a sorted string). Then just count how often each appears:

def anagram_counter(words):
    count = Counter(frozenset(Counter(word).items()) for word in words)
    return sum(choose(x, 2) for x in count.values() if x > 1)

def anagram_counter2(words):
    count = Counter("".join(sorted(word)) for word in words)
    return sum(choose(x, 2) for x in count.values() if x > 1)

You could optimize the last line by using Counter.most_common and stopping as soon as you get to the elements that appeared only once:

from itertools import takewhile

def anagram_counter3(words):
    count = Counter("".join(sorted(word)) for word in words)
    return sum(choose(x[1], 2)
               for x in takewhile(lambda t: t[1] > 1, count.most_common()))

Comparing the timings for some small input:

x = ["foo", "bar", "oof", "rab", "foobar"]
%timeit anagram_counter(x)
# 27.2 µs ± 1.4 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit anagram_counter2(x)
# 9.71 µs ± 656 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit anagram_counter3(x)
# 11.9 µs ± 492 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%timeit anagram_counter_op(x)
# 25.6 µs ± 472 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

And for some larger inputs:

import random
import string
import numpy as np

# increasing number of words, always 5 letters
x1 = [["".join(random.choices(string.ascii_lowercase, k=5)) for _ in range(n)]
     for n in np.logspace(1, 4, num=10, dtype=int)]
# increasing length of words, always 500 words
x2 = [["".join(random.choices(string.ascii_lowercase, k=n)) for _ in range(500)]
     for n in np.logspace(1, 4, num=10, dtype=int)]

(Note that both axis are logarithmic on both plots.)