Hiding and showing spreadsheet rows based on cell value I'm currently using the following code that is triggered as each cell in a column is updated.  It works fine, but takes a couple seconds for every cell, which is really cumbersome with ~200 cells to complete the sheet.  Is there any way to speed up this code?

Private Sub Worksheet_Change(ByVal Target As Range)

Application.ScreenUpdating = False
Sheet1.Cells.EntireRow.AutoFit

Dim iLastRow As Variant
Dim i As Integer
iLastRow = Range("R1:R" & Cells(Rows.Count, "R").End(xlUp).Row).Value

For i = 1 To UBound(iLastRow, 1)
    If Range("R" & i) = "Show" Then
        Rows(i).EntireRow.Hidden = False
    Else
        Rows(i).EntireRow.Hidden = True
    End If
Next

Application.ScreenUpdating = True

End Sub

You have indented the blocks, but not the scopes.

Private Sub DoSomething()
    '<~ here
End Sub

Might not be the case here, but in a module with multiple procedures, it's much easier to glance at the code and see where scopes begin & end when their contents are indented.

Application.ScreenUpdating = False

That's great: Excel isn't going to be wasting cycles repainting itself everytime you make a change. There's a problem though:

Application.ScreenUpdating = True

If there's a runtime error anywhere between these two instructions, execution jumps out of the procedure scope and ScreenUpdating never gets set back to True, and because the error is never handled, well, you have a potentially unhandled runtime error waiting to be thrown without warning in your user's face.

Right here:

If Range("R" & i) = "Show" Then

If Range("R" & i) contains an error value, VBA can't compare it to a String literal, and boom, runtime error 13, type mismatch. You should always assume that a worksheet cell can contain an error (#VALUE!, #NA, #REF!, etc.), and shield your code against that classic mistake using the IsError function:

If Not IsError(Range("R" & i)) Then

In any case, whenever you toggle Application state, the procedure should have an On Error statement that ensures state is cleanly toggled back in case of an error.

Private Sub DoSomething()
    On Error GoTo CleanFail
    Application.ScreenUpdating = False

    '...do stuff...

CleanExit:
    Application.ScreenUpdating = True
    Exit Sub
CleanFail:
    '...handle error...
    Resume CleanExit
End Sub

Dim iLastRow As Variant

This means to be a row number, and given the Systems Hungarian prefix (drop it!), it has all looks of an Integer. It should be a Long, because a 16-bit signed integer couldn't work with more than 32,767 rows - and a worksheet can have many, many more rows than that. Internally, the VBA7 runtime allocates a 32-bit integer for it anyway, so you might as well use a Long.

Except you can't.

iLastRow = Range("R1:R" & Cells(Rows.Count, "R").End(xlUp).Row).Value

Because it's actually an array, that contains every single value in column R!

That's actually not a bad idea in itself, except the only thing you're using it for, is to determine how many "cells" it contains - here:

For i = 1 To UBound(iLastRow, 1)

Write code that says what it means, and means what it says. If you name a variable "last row", make it hold the last row number - not a variant array that contains every single value in a column. Or, name it visibilityToggleColumn or something similar.

i being an Integer is also problematic. Use a Long, so you don't need to worry about how many rows there might be - there's no reason to use an Integer for this.

This Boolean assignment is a common pattern:

If Range("R" & i) = "Show" Then
    Rows(i).EntireRow.Hidden = False
Else
    Rows(i).EntireRow.Hidden = True
End If

So common, the latest 2.1 pre-release of Rubberduck includes an inspection (and a quick-fix) for it:

  Boolean literal assignment in conditional

  A member is assigned True/False in different branches of an If statement with no other statements in the conditional. Use the condition directly to assign the member instead.

Applying the quickfix turns this:

    If Range("R" & i) = "Show" Then
        Rows(i).EntireRow.Hidden = False
    Else
        Rows(i).EntireRow.Hidden = True
    End If

Into this:

    Rows(i).EntireRow.Hidden = Not (Range("R" & i) = "Show")

Which can then be simplified to this:

    Rows(i).EntireRow.Hidden = Range("R" & i) <> "Show"

Rubberduck also complains about implicit references to ActiveSheet - these are the root cause behind roughly 40%1 of all VBA questions asked on Stack Overflow, every day.

Unqualified Range, Rows, Columns, Names, and Cells calls, all implicitly refer to the ActiveSheet... when you're in a standard module. When you're in a worksheet module's code-behind, they implicitly refer to that sheet. The simple fact that the same identical code does different things depending on where it's written, should be enough to be explicit about it.

Since this is all happening behind Sheet1, IMO the ideal qualifier would be Me. So instead of this:

Sheet1.Cells.EntireRow.AutoFit

I would have that:

Me.Cells.EntireRow.AutoFit

And then here:

iLastRow = Range("R1:R" & Cells(Rows.Count, "R").End(xlUp).Row).Value

I'd have this:

iLastRow = Me.Range("R1:R" & Me.Cells(Me.Rows.Count, "R").End(xlUp).Row).Value

Note that if you're in the code-behind for Sheet1, you can interchangeably use Sheet1 and Me, ...but you shouldn't. Consistency is king. Seeing Me as a qualifier immediately reminds the reader that they're looking at code that's in a class module (a Worksheet is a class, Sheet1 is a Worksheet instance; ditto for Workbook and ThisWorkbook). On the other hand, qualifying with a specific worksheet's codename makes that code usable from anywhere, i.e. if you want to move that code from Sheet1.Worksheet_Change to the ThisWorkbook.SheetChange handler, nothing would have to change and it would work identically.

Okay got it. Now what about performance?

Worksheet manipulations are inherently slow. Reading & writing cell values is slow, and resizing and formatting cells is even slower.

Surely you know of the "hold Ctrl down" trick? Hold down the Ctrl key, click on the row headings you want to hide, right-click once, pick "hide" once, and poof all the selected rows get hidden at once!

You can do exactly the same thing in VBA, using a little Union helper function - something like this:

Private Function CombineRanges(ByVal source As Range, ByVal toCombine As Range) As Range
    If source Is Nothing Then
        Set CombineRanges = toCombine
    Else
        Set CombineRanges = Union(source, toCombine)
    End If
End Function

Now all you'll be doing with Range objects, is dereferencing them - as opposed to accessing their members and mutating their state.

Before I share the resulting code, I'd like to add that there are probably certain things you want to abstract away into other members. I'd declare module-level Const values, to avoid magic literals, and I'd probably expose a Property Get members or two, to abstract as many concepts and expose them to other code if they need to - otherwise make them Private, doesn't hurt.

So anyway, here's my version:

Option Explicit
Private Const VisibilityToggleColumn As Long = 18 'column "R"
Private Const VisibilityToggleValue As String = "Show"

Public Property Get LastRow() As Long
    LastRow = Me.Cells(Me.Rows.Count, VisibilityToggleColumn).End(xlUp).Row
End Property

Public Property Get VisibilityToggleColumnValues() As Variant
    VisibilityToggleColumnValues = Me.Range(Me.Cells(1, VisibilityToggleColumn), Me.Cells(LastRow, VisibilityToggleColumn)).Value
End Property

Private Sub Worksheet_Change(ByVal Target As Range)

    On Error GoTo CleanFail
    ToggleApplicationState False

    Me.Cells.EntireRow.AutoFit

    Dim rowsToHide As Range
    Dim rowsToShow As Range

    Dim visibilityToggleValues As Variant
    visibilityToggleValues = VisibilityToggleColumnValues

    Dim i As Long
    For i = LBound(visibilityToggleValues) To UBound(visibilityToggleValues)

        Dim currentCell As Range
        Set currentCell = Me.Cells(i, VisibilityToggleColumn)

        Dim currentToggle As Variant
        currentToggle = visibilityToggleValues(i, 1)

        If IsError(currentToggle) Then
            'if a cell contains an error, we don't want to hide it
            Set rowsToShow = CombineRanges(rowsToShow, currentCell)
        Else
            If StrComp(currentToggle, VisibilityToggleValue, vbTextCompare) = 0 Then
                Set rowsToShow = CombineRanges(rowsToShow, currentCell)
            Else
                Set rowsToHide = CombineRanges(rowsToHide, currentCell)
            End If
        End If

    Next

    If Not rowsToShow Is Nothing Then rowsToShow.EntireRow.Hidden = False
    If Not rowsToHide Is Nothing Then rowsToHide.EntireRow.Hidden = True

CleanExit:
    ToggleApplicationState True
    Exit Sub
CleanFail:
    MsgBox "Unhandled error in 'Worksheet_Change' handler: " & Err.Description, vbExclamation
    Resume CleanExit
    Resume
End Sub

Private Sub ToggleApplicationState(ByVal enabled As Boolean)
    Application.ScreenUpdating = enabled
    Application.EnableEvents = enabled
    Application.Calculation = IIf(enabled, xlCalculationAutomatic, xlCalculationManual)
End Sub

Private Function CombineRanges(ByVal source As Range, ByVal toCombine As Range) As Range
    If source Is Nothing Then
        Set CombineRanges = toCombine
    Else
        Set CombineRanges = Union(source, toCombine)
    End If
End Function

Notice I'm using the StrComp function to compare the strings with vbTextCompare - this ensures a case-insensitive comparison without the extra processing overhead of LCase/LCase$ or UCase/UCase$ conversions.

That code runs in just over 200ms2, with over 13,000 rows in column R - and there's probably still more room for improvements, but I'll leave it at that for now.

1By no scientific measurement whatsoever. It's just an extremely common mistake.

2Lazily measured with a very basic Timer diff.


Save handler without a nested "deferred antipattern" I have an application in which a user makes a change, and when they click Save they will be prompted to confirm, and the appropriate REST call will be made if they agree. The intial call to Save() returns a promise that is fulfilled if the call returned successfully, or rejected if there was an error or the user canceled the confirmation.

I've boiled my actual implementation down to an equivalent example in order to highlight the (anti)pattern:

//assume confirm() and commit() are functions that return a promise:
//confirm() will be fulfilled or rejected based on a user choice
//commit() will be fulfilled or rejected based on the response from a RESTful web call

function save() {
    var deferred = $q.defer();

    confirm().then(function(response) {
        commit().then(function(response) {
            deferred.resolve();
        }).catch(function(rejection) {
            deferred.reject(rejection);
        });
    }, function(rejection) {
        deferred.reject(rejection);
    });

    return deferred.promise;
};

This stuck out to me rather clearly as the deferred antipattern, and so I refactored it to this:

function save() {
    var deferred = $q.defer();

    confirm().then(function(response) {
        deferred.resolve(commit());
    }, function(rejection) {
        deferred.reject(rejection);
    });

    return deferred.promise;
};

Subsequently, it still looked like the deferred antipattern, and after a little while of thinking and Googling, I reduced it to this:

function save() {
    return confirm().then(function(response) {
        return commit();
    }, function(rejection) {
        return $q.reject(rejection);
    });
};

Now, that looks pretty good to me, but I'm not sure if it's as good as it can be. All three versions above are functional, but is there perhaps a fourth iteration that would reduce it even further, or is this the simplest form for this depth of promises?

I've created a fiddle here for anyone who may want to see it in action.

You can also leave out reject. Your code would look like:

function save() {
    return confirm().then(function(response) {
        return commit();
    });
};

The promise returned by then() will automatically be rejected if the promise returned by confirm() is rejected.

Combining with @ShaunH's answer you would be left with

function save() {
    return confirm().then(commit);
};


Login module with JDBC I made simple login module that is responsible for handling registration, and signing in my application. How can I improve this code? Are there any conventions for this case?

The idea is to create siteUser and link him to his unique Account with cash info. Then let him login to app.

package auctionsite.login;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import auctionsite.stuff.IRegister;

public class LoginHandler implements IRegister {
    public static LoginHandler instance = null;
    private static final String DB_URL = "jdbc:derby:auction_site;create=true";
    private Connection conn = null;

    public static LoginHandler getInstance() {
        return instance == null ? new LoginHandler() : instance;
    }

    private int getUserID(String username) {
        try {
            Connection conn = DriverManager.getConnection(DB_URL);
            PreparedStatement prepStmt = conn.prepareStatement("SELECT userId FROM SiteUser WHERE name =?");
            prepStmt.setString(1, username);
            ResultSet rs = prepStmt.executeQuery();
            rs.next();
            return rs.getInt(1);

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    private void insertNewUser(String username, String pass) {
        try {
            Connection conn = DriverManager.getConnection(DB_URL);
            PreparedStatement prepStmt = conn.prepareStatement("INSERT INTO SiteUser (name,password) VALUES (?,?)");
            prepStmt.setString(1, username);
            prepStmt.setString(2, pass);
            prepStmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void createAccountForUser(String username) {
        try {
            Connection conn = DriverManager.getConnection(DB_URL);
            PreparedStatement prepStmt = conn.prepareStatement("INSERT INTO PaymentAccount (cash,userId) VALUES (?,?)");
            prepStmt.setDouble(1, 0.00);
            prepStmt.setInt(2, getUserID(username));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int register(String username, String pass) {
        PreparedStatement prepStmt = null;
        try {
            conn = DriverManager.getConnection(DB_URL);
            prepStmt = conn.prepareStatement("SELECT COUNT(*) FROM SiteUser WHERE name=?");
            prepStmt.setString(1, username);
            ResultSet rs = prepStmt.executeQuery();
            rs.next();
            if (rs.getInt(1) <= 0) {
                if (validatePass(pass) && validateUsername(username)) {
                    insertNewUser(username, pass);
                    createAccountForUser(username);
                    return 1;
                } else {
                    return 0;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    private boolean validateUsername(String username) {
        return username.length() > 3;
    }

    private boolean validatePass(String pass) {
        return pass.length() >= 10 & pass.matches(".*\\d+.*");
    }

    @Override
    public void delete() {
    }

    @Override
    public int login(String userName, char[] pass) {
        try {
            conn = DriverManager.getConnection(DB_URL);
            PreparedStatement prepStmt = conn
                    .prepareStatement("SELECT name,password FROM SiteUser WHERE name=? AND password=?");
            prepStmt.setString(1, userName);
            prepStmt.setString(2, new String(pass));
            ResultSet rs = prepStmt.executeQuery();
            if (rs.next()) {
                return 1;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}

Checking return values

A mistake I see in multiple places is not checking the return values of operations.

Take for example the part of getting the user ID:

PreparedStatement prepStmt = conn.prepareStatement("SELECT userId FROM SiteUser WHERE name =?");
prepStmt.setString(1, username);
ResultSet rs = prepStmt.executeQuery();
rs.next();
return rs.getInt(1);

Before getting values from a ResultSet instance,
you should always check the return value of rs.next(),
as explained in the official JDBC tutorial.

Without that check, the rs.getInt(1) statement will raise SQLException when there is no matching user.
Since you wrapped the block of code in try { ... } catch (SQLException e) { ... }, the exception will be handled, but this is not appropriate use of exceptions.

The purpose of the try-catch is not to handle the case of no matching user.
Its purpose is to handle unexpected errors during the database operation.
If you rely on this try-catch to handle the case of no matching user,
that's effectively using exceptions for flow control.
That's not the intended use, and it's also inefficient,
as it's slower than using a conditional to check the value of rs.next().

I suggest to review the entire code, look for statements where a function returns a value but you don't use it. Some IDEs for example IntelliJ will give you a warning on statements like that.

Another form of not checking the return value is in the process of registering a user. Consider this snippet from the register method:

insertNewUser(username, pass);
createAccountForUser(username);

The insertNewUser doesn't return anything,
but probably it should.
Inserting a new user might not succeed,
and it would be incorrect to create an account if the user could not be created.

Potentially unsafe register

The implementation looks prone to a race condition:
in between the moment of checking if the username exists,
and the moment of inserting the user,
another process or program may have inserted a user with the same name.
In fact,
unless you wrap these two operations within a transaction,
there's no way to safely guarantee that the insert operation will succeed.

I'm not sure if you have a unique index on the username column.
If you do, then you could skip checking if the user exists,
attempt to insert.
If the insert is successful, the user did not exist, it was successfully inserted, and you can continue creating the account.
If the insert fails, whether because the user already exists, or due to other database errors, you can abort further processing.

Connection management

Creating connections is an expensive operation.
Avoid creating new connections unnecessarily as much as possible.
It might be a good idea to manage the connection outside this class.
Or if you really want to create it in this class,
make sure that a chain of operations reuses the same connection,
rather than recreating it in each step.

Ordering of operations

The register method first checks if the specified username exists,
and then validates the username and the password against some built-in rules.
It would be better to perform these operations in the opposite order.
The validation logic is a cheap operation,
database lookups are expensive.

Confusing member and local variables

Some methods reuse the conn field,
others create it as a local variable.
This is confusing.


Finding number of palindrome pairs in an array I am trying to find the number of string pairs in an array that are palindromes.

import java.io.BufferedReader;
import java.io.InputStreamReader;

class TestClass {
public static void main(String args[] ) throws Exception {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String line = br.readLine();
    int N = Integer.parseInt(line);

    int count = 0;

    String s[] = new String[N];

    for (int i = 0; i < N; i++) {
        s[i] = br.readLine();
    }

    for (int i = 0; i < N; i++) {
        String str = s[i];

        for(int j=i; j<N; j++) {

            StringBuilder sb = new StringBuilder(s[j]);
            if(str.equals(sb.reverse().toString())){
                count++;
            }
        }
    }

    System.out.print(count);
}
}

Is there a more efficient way to do this?

Is there a more efficient way to do this?

At the moment you have an \$O(N^2)\$ algorithm as you can see from the nested loops up to N This is not as efficient as it could be.

What you should have is an \$O(N \log N)\$ or \$O(N)\$ algorithm. To achieve \$O(N)\$, you need to pass over the words just once, ideally as you read them avoiding the need for a String[]. To do this, you need to store the words in a data structure with \$O(1)\$ (at least amortized) access. e.g. a HashSet or a HashMap.

It could look like this:

start with a HashSet of words so far. initially empty.
for each word *as you read it*.
   compute its palindrome.
   remove this palidrome from the set
   and see if it was there. i.e. Set.remove(reverse) will do this.
   if it was there you have a match
   otherwise add the word to the set.
done

Instead of three loops, you only need one.

You can see that you pass over the words just once and each operation is \$O(1)\$ with the number of words. This assumes that the words length has some natural upper bound and the length of the words doesn't matter.


Compute mean, variance and standard deviation of CSV number file I've written my first C++ application this week and I wanted to see if there's anything that aren't up to standards or better ways to do what I'm currently doing.

For the goal of the exercise, let's assume I can't use any other mathematical function other than the square root.

The application reads a file where numbers are on separate lines and computes the mean, variance and standard deviation of all the numbers. Afterwards I print the whole numbers list and the stats that were computed.

#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#import <cmath>

using namespace std;

std::vector<int> readFile(const std::string &filePath) {
    ifstream in_file;
    in_file.open(filePath);
    std::vector<int> numbers;

    std::string line;

    while(std::getline(in_file,line,'\r')){
        numbers.push_back(std::stoi(line));
    }

    return numbers;
}

float computeMean(std::vector<int> numbers)
{
    if(numbers.empty()) return 0;

    float total = 0;
    for (int number : numbers) {
        total += number;
    }

    return (total / numbers.size());
}

float computeVariance(float mean, std::vector<int> numbers)
{
    float result = 0;
    for(int number : numbers)
    {
        result += (number - mean)*(number - mean);
    }

    return result / (numbers.size() - 1);
}

int main() {
    std::cout << "Please enter the file path :" << std::endl;
    std::string filePath;
    std::cin >> filePath;
    std::vector<int> numbers = readFile(filePath);
    float mean = computeMean(numbers);
    float variance = computeVariance(mean, numbers);
    float standardDeviation = sqrt(variance);

    std::cout << std::to_string(numbers.size()) + " numbers : ";
    std::string data;
    for(int number : numbers) {
        data += std::to_string(number) + ", ";
    }
    data = data.substr(0, data.length()-2);
    std::cout << data << std::endl;

    std::cout << "Mean : " << std::to_string(mean) << std::endl;
    std::cout << "Variance : " << std::to_string(variance) << std::endl;
    std::cout << "Standard Deviation : " << std::to_string(standardDeviation) << std::endl;
    return 0;
}

Portability

#import is a GCC extension (or perhaps a preview of C++20).

There's no good reason not to simply #include <cmath> here.

Headers and namespaces

We don't use any string-stream, so #include <sstream> can be removed.

Bringing all names in from a namespace is problematic; namespace std particularly so.  It can silently change the meaning of your program when you're not expecting it.  Get used to using the namespace prefix (std is intentionally very short), or importing just the names you need into the smallest reasonable scope.

In this program, the only places the std:: prefix were missing were std::ifstream and std::sqrt, so this wasn't hard to fix.

readFile()

These lines can be simplified:

std::ifstream in_file;
in_file.open(filePath);

We can ask the constructor to open the file for us:

std::ifstream in_file(filePath);

This loop has some error checking, but it's not complete:

while(std::getline(in_file,line,'\r')){
    numbers.push_back(std::stoi(line));
}

Firstly, we don't expect any carriage-return in the input file (we opened it in text mode, so on systems that use CR as line delimiter, they will be converted to \n).  Secondly, std::stoi throws exceptions when the string cannot be converted, but we probably also want to check whether there are leftover, unconverted characters after our integer (e.g. if someone thought they could supply decimal values).

computeMean()

Why return a float rather than double?  Single-precision floats are normally used only where the storage size is an important consideration, which is not the case here.  (Note that on many platforms, double is the natural (and fastest) size of floating-point.)

We should pass the vector by reference to a const object, as we don't want to make a copy or to modify the value.

Instead of returning zero when there are no members, perhaps we should return a NaN value (which is more consistent with arithmetic 0.0 / 0):

if (numbers.empty())
    return std::numeric_limits<double>::quiet_NaN();

This loop:

double total = 0;
for (int number : numbers) {
    total += number;
}

can be written (with #include <numeric>) as

double total = std::accumulate(numbers.begin(), numbers.end(), 0.0);

computeVariance()

We need to be clear which variance (sample or population) we're returning.  We're also missing a size check similar to that for the mean.

Apart from that, the comments above for computeMean() are relevant:

double computeSampleVariance(const double mean, const std::vector<int>& numbers)
{
    if (numbers.size() <= 1u)
        return std::numeric_limits<double>::quiet_NaN();

    auto add_square = [mean](double sum, int i)
        {
            auto d = i - mean;
            return sum + d*d;
        };
    double total = std::accumulate(numbers.begin(), numbers.end(), 0.0, add_square);
    return total / (numbers.size() - 1);
}

Single-pass algorithm

It is possible to compute the mean and variances in a single pass - but not using the (exact-arithmetic) methods you likely learnt in high school, which suffer from lack of precision with the inexact floating-point types we can use.  The topic is too deep for this review, but if you research Welford's Algorithm, you will find reference implementations to guide you.

That said, for your purposes, the straightforward two-pass algorithm is probably appropriate, and it's easy to read and understand, so I wouldn't recommend changing it unless you reach a point where your input set becomes too large to hold in a vector (and even then, only if you can't read the file multiple times).

My version

#include <algorithm>
#include <cmath>
#include <fstream>
#include <iostream>
#include <iterator>
#include <limits>
#include <numeric>
#include <vector>

std::vector<int> readFile(const std::string& filePath)
{
    std::ifstream in_file(filePath);
    std::istream_iterator<int> start{in_file}, end;
    std::vector<int> numbers;
    std::copy(start, end, std::back_inserter(numbers));
    return numbers;
}

double computeMean(const std::vector<int>& numbers)
{
    if (numbers.empty())
        return std::numeric_limits<double>::quiet_NaN();

    return std::accumulate(numbers.begin(), numbers.end(), 0.0) / numbers.size();
}

double computeSampleVariance(const double mean, const std::vector<int>& numbers)
{
    if (numbers.size() <= 1u)
        return std::numeric_limits<double>::quiet_NaN();

    auto const add_square = [mean](double sum, int i) {
        auto d = i - mean;
        return sum + d*d;
    };
    double total = std::accumulate(numbers.begin(), numbers.end(), 0.0, add_square);
    return total / (numbers.size() - 1);
}

int main()
{
#ifdef TEST
    const std::vector<int> numbers = { -2, -1, 1, 2, 100000-2, 100000-1, 100000+1, 100000+2};
#else
    std::cout << "Please enter the file path :" << std::endl;
    std::string filePath;
    std::cin >> filePath;
    const std::vector<int> numbers = readFile(filePath);
#endif

    double mean = computeMean(numbers);
    double variance = computeSampleVariance(mean, numbers);
    double standardDeviation = std::sqrt(variance);

    std::cout << numbers.size() << " numbers : ";
    auto separator = "";
    for (int number: numbers) {
        std::cout << separator << number;
        separator = ", ";
    }
    std::cout << std::endl;

    std::cout << "Mean : " << std::to_string(mean)
              << "Variance : " << std::to_string(variance)
              << "Standard Deviation : " << std::to_string(standardDeviation) << std::endl;
    return 0;
}


"Rock, Paper, Scissors" game - follow-up This is a follow-up to ""Rock, Paper, Scissors" game". I did almost everything the answers recommended and I hope you like it.

import os
from random import choice

def player_choice():
    while True:
        print("Rock, paper or scissors?")
        choice = input(">").capitalize()
        if choice in ('Rock', 'Paper', 'Scissors'):
            return choice

def win_msg(player_choice, computer_choice):
    msg = f"{player_choice} beats {computer_choice}. You won!"
    return msg

def lose_msg(player_choice, computer_choice):
    msg = f"{computer_choice} beats {player_choice}. You lost!"
    return msg

def computer_choice():
    return choice(('Rock', 'Paper', 'Scissors'))

def show_statistics(scores):
    os.system('cls' if os.name == 'nt' else 'clear')
    print(f"Wins: {scores[0]}\nLosses: {scores[1]}\nDraws: {scores[2]}")

def game_outcome(player, computer):
    if player == computer:
        return 'Draw'
    elif player == 'Rock':
        if computer == 'Paper':
            return 'Lose'
        else:
            return 'Win'
    elif player == 'Paper':
        if computer == 'Rock':
            return 'Win'
        else:
            return 'Lose'
    else:
        if computer == 'Rock':
            return 'Lose'
        else:
            return 'Win'

def show_results(outcome, player, computer):
    if outcome == 'Win':
        print(win_msg(player, computer))
    elif outcome == 'Lose':
        print(lose_msg(player, computer))
    else:
        print("Draw. Nobody wins or losses.")

def update_scores(scores, outcome):
    new_scores = list(scores)
    if outcome == 'Win':
        new_scores[0] += 1
    elif outcome == 'Lose':
        new_scores[1] += 1
    else:
        new_scores[2] += 1
    new_scores = tuple(new_scores)
    return new_scores

def rock_paper_scissors(scores):
    player = player_choice()
    computer = computer_choice()
    outcome = game_outcome(player, computer)
    show_results(outcome, player, computer)
    new_scores = update_scores(scores, outcome)
    return new_scores

def play_again():
    while True:
        print("\nDo you want to play again?")
        print("(Y)es")
        print("(N)o")
        ans = input("> ").lower()
        if ans == 'y':
            return True
        elif ans == 'n':
            return False

def starting_scores():
    return 0, 0, 0

def main():
    scores = starting_scores()
    still_playing = True
    while still_playing:
        show_statistics(scores)
        scores = rock_paper_scissors(scores)
        still_playing = play_again()

if __name__ == '__main__':
    main()

Firstly, this is some nice clean code. Well done.

The changes I'd make:

win_msg and lose_msg can instead be global constant strings.
You should pick a preferred string delimiter and stick to using just that one. I prefer '.
I would make a function clear_console as the code is rather strange. And will ease use if you need it again.
game_outcome can be simplified by using a dictionary to store what beats what.

This also means you can expand to RPSLS with ease.
show_results can be changed to use a dictionary too.
update_scores can be changed in one of two ways:

Add a dictionary that converts from outcome to the index.
Change scores to a dictionary.

And so you can get the following code:

import os
from random import choice

MESSAGES = {
    'Win': '{player} beats {computer}. You won!',
    'Lose': '{computer} beats {player}. You lost!',
    'Draw': 'Draw. Nobody wins or losses.'
}

BEATS = {
    'Rock': 'Scissors',
    'Paper': 'Rock',
    'Scissors': 'Paper'
}

def player_choice():
    while True:
        print('Rock, paper or scissors?')
        choice = input('>').capitalize()
        if choice in ('Rock', 'Paper', 'Scissors'):
            return choice

def play_again():
    while True:
        print('\nDo you want to play again?')
        print('(Y)es')
        print('(N)o')
        ans = input('> ').lower()
        if ans == 'y':
            return True
        elif ans == 'n':
            return False

def computer_choice():
    return choice(('Rock', 'Paper', 'Scissors'))

def clear_console():
    os.system('cls' if os.name == 'nt' else 'clear')

def game_outcome(player, computer):
    if player == computer:
        return 'Draw'

    if BEATS[player] == computer:
        return 'Win'
    else:
        return 'Lose'

def rock_paper_scissors(scores):
    clear_console()
    print(f'Wins: {scores["Win"]}\nLosses: {scores["Lose"]}\nDraws: {scores["Draw"]}')
    player = player_choice()
    computer = computer_choice()
    outcome = game_outcome(player, computer)
    print(MESSAGES[outcome].format(player=player, computer=computer))
    scores[outcome] += 1
    return new_scores

def main():
    scores = {
        'Win': 0,
        'Lose': 0,
        'Draw': 0
    }
    still_playing = True
    while still_playing:
        scores = rock_paper_scissors(scores)
        still_playing = play_again()

if __name__ == '__main__':
    main()

From here you can look into using enum to remove the strings from your code. This is good because it's easy to make a typo in a string, say I use 'rock' rather than 'Rock'. It also means that if you do make a typo then you'll be able to see where it was made when you reach that code. However with a string it'll move the error to a later part of the code and make debugging horrible.

Here is an example of how you can use them:

from enum import Enum

class Score(Enum):
    WIN = 'Win'
    LOSE = 'Lose'
    DRAW = 'Draw'

MESSAGES = {
    Score.WIN: '{player} beats {computer}. You won!',
    Score.LOSE: '{computer} beats {player}. You lost!',
    Score.DRAW: 'Draw. Nobody wins or losses.'
}


K’th SmallestElement in Unsorted Array in python I was solving this sorting problem, and I was wondering if I can get any code review and feedback. You can find this problem online.

#  Find Kth Smallest Element in a Range
#
#  Prompt:    Given an unsorted array of whole integers in the range
#             1000 to 9000, find the Kth smallest element in linear time
#             The array can have duplicates.
#
#  Input:     Unsorted array of whole integers in range of 1000 to 9000
#             Kth smallest element you want to find
#
#  Output:    Kth smalest element in the range
#
#  Example:   array = [1984, 1337, 9000, 8304, 5150, 9000, 8304], k=5
#             output = 8304
#
#  Notes:     What are the time and auxilliary space complexity?

# Time Complexity: O(N)
# Auxiliary Space Complexity: O(N)

def kthSmallest(lst, k):
    if k > len(lst):
        return None
    int_counts = [0 for x in range(8001)]
    for i in range(len(lst)):
        int_counts[lst[i] - 1000] += 1
    cumulative = []
    prev = 0
    for i in range(len(int_counts)):
        cumulative.append(int_counts[i] + prev)
        prev += int_counts[i]
    for i in range(len(lst) - 1, -1, -1):
        if cumulative[lst[i] - 1000] - 1 == k - 1:
            return lst[i]
        cumulative[lst[i] - 1000] -= 1

it passes all of the following test

from cStringIO import StringIO
import sys
import random

# code for capturing print output
#
# directions: capture_print function returns a list of all elements that were
#             printed using print with the function that it is given. Note that
#             the function given to capture_print must be fed using lambda.
#             Example cis provided below
class Capturing(list):
    def __enter__(self):
        self._stdout = sys.stdout
        sys.stdout = self._stringio = StringIO()
        return self

    def __exit__(self, *args):
        self.extend(self._stringio.getvalue().splitlines())
        sys.stdout = self._stdout

# custom assert function to handle tests
# input: count {List} - keeps track out how many tests pass and how many total
#        in the form of a two item array i.e., [0, 0]
# input: name {String} - describes the test
# input: test {Function} - performs a set of operations and returns a boolean
#        indicating if test passed
# output: {None}
def expect(count, name, test):
    if (count is None or not isinstance(count, list) or len(count) != 2):
        count = [0, 0]
    else:
        count[1] += 1

    result = 'false'
    error_msg = None
    try:
        if test():
            result = ' true'
            count[0] += 1
    except Exception, err:
        error_msg = str(err)

    print('  ' + (str(count[1]) + ')   ') + result + ' : ' + name)
    if error_msg is not None:
        print('       ' + error_msg + '\n')

print('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\n\n')

print('Kth Smallest Element Tests')
test_count = [0, 0]

def test():
    example = kthSmallest([1984, 1337, 9000, 8304, 5150, 9000, 8304], 5)
    return example == 8304

expect(test_count, 'should return 8304 for sample input', test)

def test():
    example = kthSmallest([1984, 1337, 9000, 8304, 5150, 9000, 8304], 1)
    return example == 1337

expect(test_count, 'should return 1337 for 1st smallest element with sample input array', test)

def test():
    example = kthSmallest([1984, 1337, 9000, 8304, 5150, 9000, 8304], 10)
    return example == None

expect(test_count, 'should error out when asking for kth smallest when k exceeds size of input array', test)

def test():
    example = kthSmallest([8304], 1)
    return example == 8304

expect(test_count, 'should work for single-element array', test)

def test():
    test_case = []
    for i in range(0, 1000000):
        test_case.append(int(random.random() * 8000) + 1000)
    example = kthSmallest(test_case, 185)
    test_case.sort()
    return example == test_case[184]

expect(test_count, 'should work for a large array', test)

print('PASSED: ' + str(test_count[0]) + ' / ' + str(test_count[1]) + '\n\n')

There is no need to have a cumulative array. Using append repeatedly is also no such a great idea, because of the cost of memory reallocation.

def kthSmallest(lst, k):
    if k > len(lst):
        return None
    int_counts = [0 for x in range(8001)]
    for i in range(len(lst)):
        int_counts[lst[i] - 1000] += 1
    cumulative = 0
    for i in range(len(int_counts)):
        cumulative += int_counts[i]
        if cumulative >=  k:
            return i + 1000


Bring phone numbers in consistent format I'm using this code to bring my phone numbers in a consistent format.

Desired: +(country code)phone number

Possible patterns:

01721234567 -> change to desired pattern
00491234567 -> change to desired pattern
+4912345678 -> do nothing, already desired pattern

This is what I use:
String number = allContactNumbers.get(i).get(j);
number = number.replaceAll("[^+0-9]", ""); // All weird characters such as /, -, ...

String country_code = getResources().getString(R.string.countrycode_de);

if (number.substring(0, 1).compareTo("0") == 0 && number.substring(1, 2).compareTo("0") != 0) {
    number = "+" + country_code + number.substring(1); // e.g. 0172 12 34 567 -> + (country_code) 172 12 34 567
}

number = number.replaceAll("^[0]{1,4}", "+"); // e.g. 004912345678 -> +4912345678

For some reason I'm not happy with it though. I hope there is somebody to tell me, whether my code is written properly!

There are two aspects to this, the general design, and the implementation.
Implementation
The entire things should be extracted as a function. The first line of code:

String number = allContactNumbers.get(i).get(j);

indicates that this code is being run inside a loop (i,j). You need to extract it to be:
String number = normalizePhoneNumber(allContactNumbers.get(i).get(j));

and the function would look something like:
public String normalizePhoneNumber(String number) {
    ......
    return normalized;
}

Right, about that function, putting your code in it ends up with:
public String normalizePhoneNumber(String number) {

    number = number.replaceAll("[^+0-9]", ""); // All weird characters such as /, -, ...

    String country_code = getResources().getString(R.string.countrycode_de);

    if (number.substring(0, 1).compareTo("0") == 0 && number.substring(1, 2).compareTo("0") != 0) {
        number = "+" + country_code + number.substring(1); // e.g. 0172 12 34 567 -> + (country_code) 172 12 34 567
    }

    number = number.replaceAll("^[0]{1,4}", "+"); // e.g. 004912345678 -> +4912345678

    return number;
}

Design
OK, about the design.... I believe this is a problem. Handling phone numbers is much more complicated than what you have.... it is really a challenging problem.
It is easy enough to strip off the junk, but it gets hard really fast. For example, this is the the Queen of England's land-line number (not kidding):

Public Information Officer
Buckingham Palace
London SW1A 1AA
Tel (during 9am - 5pm (GMT) Monday to Friday): (+44) (0)20 7930 4832. Please note, calls to this number may be recorded.

As a Canadian, the international dialing code for this would be:
01144207934832

How will your script translate that in to:
+442079305832

I think you need to revise your plan for this problem, it is more complicated than you realize.


Converting the integers to their equivalent string representations I have the following function which converts an integer (such as 103) to its string representation ("one hundred three"):

NumberToString = (function ()
    local floor, abs, num, tens, bases = math.floor, math.abs, {
        [0] = '',
        'one',
        'two',
        'three',
        'four',
        'five',
        'six',
        'seven',
        'eight',
        'nine',
        'ten',
        'eleven',
        'twelve',
        'thirteen',
        'fourteen',
        'fifteen',
        'sixteen',
        'seventeen',
        'eighteen',
        'nineteen',
        'twenty'
    }, {
        [0] = 'and',
        [3] = 'thirty',
        [4] = 'forty',
        [5] = 'fifty',
        [6] = 'sixty',
        [7] = 'seventy',
        [8] = 'eighty',
        [9] = 'ninety',
    }, {

        [10^2] = ' hundred',
        [10^3] = ' thousand',
        [10^6] = ' million'
    }
    return function(n)
        local n = floor( abs(n) )
        local str = {}
        if n > 10^6 then
            table.insert( str, NumberToString(n / 10^6)..bases[10^6] )
            n = n % 10^6
        end
        if n > 10^3 then
            table.insert( str, NumberToString(n / 10^3)..bases[10^3] )
            n = n % 10^3
        end
        if n > 10^2 then
            table.insert( str, NumberToString(n / 10^2)..bases[10^2] )
            n = n % 10^2
        end
        if num[n] then
            table.insert( str, num[n] )
        else
            table.insert( str, tens[floor(n/10)]..' '..(n % 10 > 0 and num[n % 10] or '') )
        end
        return table.concat(str, ' ')
    end
end)()

Can I improve the performance somehow? Or does some other (and better method) exist for the desired results?

I think that the segment between line #43 to #53 is quite redundant and can be modified?

After a bit of dabbling with the script, I've updated the line #42 to #53 with a table iterator:

for _, ext in ipairs(bases) do
    if n > ext[1] then
        table.insert( str, NumberToString(n / ext[1])..ext[2] )
        n = n % ext[1]
    end
end

where, bases has been redefined as:

{
    { 10^12, ' trillion' },
    { 10^9, ' billion' },
    { 10^6, ' million' },
    { 10^3, ' thousand' },
    { 10^2, ' hundred' },
}

that is, in descending orders of powers of 10.

I'd welcome other suggestions as well.


Implementation of concurrent blocking queue for producer-consumer I've implemented concurrent_blocking_queue  for multiple-producers and single consumer.

I intend it to block the producers as well, when the queue is full, which is why I set the capacity of the queue in the constructor. I've provided my own implementation of critical_section, scoped_lock and condition_variable, using msdn primitives.

Please review it. I want to know if there is any potential deadlocks.

template<typename T>
class concurrent_blocking_queue : public noncopyable
{
    std::queue<T> m_internal_queue;
    mutable critical_section m_critical_section;
    condition_variable m_queue_full;
    condition_variable m_queue_empty;
    const size_t m_capacity;
public:
    concurrent_blocking_queue(size_t capacity)
        : m_capacity(capacity), m_critical_section()
    {
    }
    void put(T const & input)
    {
        framework::scoped_lock lock(m_critical_section); //lock
        m_queue_full.wait(lock, [&]{ return !full(); });
        m_internal_queue.push(input);
        m_queue_empty.notify_all();
    }
    T take()
    {
        framework::scoped_lock lock(m_critical_section); //lock
        m_queue_empty.wait(lock, [&]{ return !empty(); });
        T output = m_internal_queue.front();
        m_internal_queue.pop();
        m_queue_full.notify_all();
        return output;
    }
    bool full() const
    {
        framework::scoped_lock lock(m_critical_section);
        if ( m_internal_queue.size() > m_capacity )
        {
            throw std::logic_error("size of concurrent_blocking_queue cannot be greater than the capacity.");
        }
        return m_internal_queue.size() == m_capacity;
    }
    bool empty() const
    {
        framework::scoped_lock lock(m_critical_section);
        return m_internal_queue.empty();
    }
    //..
};

And the remaining classes are posted below. Note that I've implemented them in .h and .cpp files, but here I've merged them to make the post short and simple, and have removed the namespace for brevity, otherwise all classes are defined in framework namespace.

critical_section derives publicly from CRITICAL_SECTION.

class critical_section : public CRITICAL_SECTION, public noncopyable
{
 public:
    critical_section(void) { ::InitializeCriticalSection(this); }
    ~critical_section(void) { ::DeleteCriticalSection(this); }
    void lock() { ::EnterCriticalSection(this); }
    void unlock() { ::LeaveCriticalSection(this); }
};

condition_variable derives privately from CONDITION_VARIABLE.

class condition_variable : private CONDITION_VARIABLE, public noncopyable
{
 public:
    condition_variable() { ::InitializeConditionVariable(this); }
    ~condition_variable(void) {}
    void wait(scoped_lock & lock)
    {
       if (!::SleepConditionVariableCS (this, &lock.m_cs, INFINITE))
       {
          DWORD error = ::GetLastError();
          std::string msg = format("SleepConditionVariableCS() failed with error code = 0x%X.", error);
          throw std::runtime_error(msg);
       }
    }
    void wait(scoped_lock & lock, std::function<bool()> predicate)
    {
       while( !predicate() )  {  wait(lock);  }
    }
    void notify_one() { ::WakeConditionVariable(this); }
    void notify_all() { ::WakeAllConditionVariable(this); }
};

scoped_lock

class scoped_lock : public noncopyable
{
   friend class condition_variable;
   critical_section & m_cs;
 public:
   scoped_lock(critical_section & cs) : m_cs(cs) { m_cs.lock(); }
   ~scoped_lock(void) { m_cs.unlock(); }
};

Basic comments:
No point in functions that do nothing.
Also avoid void as definition for empty parameter list.
~condition_variable(void) {}

Why put a member that has no default constructor in the initializer list ( I can go either way)
concurrent_blocking_queue(size_t capacity)
    : m_capacity(capacity), m_critical_section()

But you should be consistent and thus if you do it for one then you should do it for all members.
Design:
When you call full() and empty() from within other members you already have a lock. Yet you are calling a function that will add another level of locking. And locking is usually relatively expensive.
    m_queue_full.wait(lock, [&]{ return !full(); });

    m_queue_empty.wait(lock, [&]{ return !empty(); });

Thus I would change the above to call a private version of these function that do not use locks.
    // OLD STUFF
    m_queue_full.wait(lock, [&]{ return !test_full(); });

    // OLD STUFF
    m_queue_empty.wait(lock, [&]{ return !test_empty(); });

    bool full() const
    {
      framework::scoped_lock lock(m_critical_section);
      return test_full();
    }
    bool empty() const
    {
      framework::scoped_lock lock(m_critical_section);
      return test_empty();
    }

    private:
    bool test_full()  const {STUFF}
    bool test_empty() const {STUFF}


user-facing email validation I'd like to have a generic way for validating user provided email with a bias toward ease of use. Does the following do so in a clear way for implementations that have the URL interface available? The sample input below is only intended to exercise the range of expected input and demonstrate it works. The UI is not in scope and varies separately--the solution is only intended to provide input validation with usable feedback for implementations.
Any feedback welcome on the style, approach, etc.
function validEmail(input=''){
    const emailPatternInput = /^[^@]{1,64}@[^@]{4,253}$/, emailPatternUrl = /^[^@]{1,64}@[a-z][a-z0-9\.-]{3,252}$/i;
    let email, url, valid = false, error, same = false;
    try{
        email = input.trim();
        // handles punycode, etc using browser's own maintained implementation
        url = new URL('http://'+email);
        let urlderived = `${url.username}@${url.hostname}`;
        same = urlderived === email;
        valid = emailPatternInput.test( email );
        if(!valid) throw new Error('invalid email pattern on input:' + email);
        valid = emailPatternUrl.test( urlderived );
        if(!valid) throw new Error('invalid email pattern on url:' + urlderived);
    }catch(err){
        error = err;
    };
    return {email, url, same, valid, error};
}

[
 'user+this@はじめよう.みんな'
, 'stuff@things.eu'
, 'stuff@things'
, 'user+that@host.com'
, 'Jean+François@anydomain.museum','هيا@יאללה'
, '试@例子.测试.مثال.آزمایشی'
, 'not@@really'
, 'no'
].forEach(email=>console.log(validEmail(email), email));

I would avoid the habit of declaring multiple variables in the same line. In most cases, they're hard to read especially when they get long. The only one exception I'd do this would be if everything is short enough to read, like your let line. But that one has other issues as well: why the two falses? and why initialize with false when they end up as other types (string for email and url, and an Error instance for error)?
A general rule for try-catch is to only use it for unexpected errors, like for calls to other functions. Never use it as a control structure. In your case, you're using thrown errors to bail out of the block. Throwing an error inside your own try-catch is an anti-pattern. It's better to use a conditional instead.
Then theres the inconsistent use of syntax, like the use of template literals here but not there, or the one-time assignments to a let which can just be a const, etc.
Now, doing away with the try-catch, the only thing that's complex is the relationship between error and valid. Everything else is just a value resulting from an expression, which in the following example... is just a series of const.
In your code, you compute validity twice and determine which error to use based on which check failed. This probably led to the strange complexity in your version of the code, you had to bail out with your error before it did the next check. But you can flip it around. You can use the check to determine the error. Then define valid based on the presence or absence of that error.

function validEmail(input = '') {
  const inputPattern = /^[^@]{1,64}@[^@]{4,253}$/
  const emailPattern = /^[^@]{1,64}@[a-z][a-z0-9\.-]{3,252}$/i
  const email = input.trim()

  // handles punycode, etc using browser's own maintained implementation
  const url = new URL(`http://${email}`)
  const urlDerived = `${url.username}@${url.hostname}`

  // Same-ness is the same regardless of errors. Bumping up.
  const same = urlDerived === email;

  // Test for incorrectness, null if ok.
  const error = !inputPattern.test(email) ? new Error(`invalid email pattern on input: ${email}`)
    : !emailPattern.test(urlDerived) ? new Error(`invalid email pattern on url: ${urlDerived}`)
    : null

  // The presence/absence of the error determines validity.
  const valid = !Boolean(error)

  return { email, url, same, valid, error }
}

[
  'user+this@はじめよう.みんな',
  'stuff@things.eu',
  'stuff@things',
  'user+that@host.com',
  'Jean+François@anydomain.museum',
  'هيا@יאללה',
  '试@例子.测试.مثال.آزمایشی',
  'not@@really',
  'no'
].forEach(email => console.log(validEmail(email), email));


Printing longest lines Challenge
Write a program which reads a file and outputs a specified number of lines, sorted on length in descending order.
Specifications

The first argument is a path to a file.
The file contains multiple lines.
The first line indicates the number of lines to output.
The following lines are of differing lengths and presented randomly.
Print the specified number of lines in descending order of length.

Constraints

The number in the first line is a valid positive integer.
The input file is correctly formatted.

Input Sample

2
Hello World
Code Reviews
Quick Fox
A
San Francisco

Output Sample

San Francisco
Code Reviews

Source
Solution:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.NavigableMap;
import java.util.Scanner;
import java.util.TreeMap;

public class Solution {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(new File(args[0]));
        int numberOfLinesToPrint = Integer.parseInt(input.nextLine());

        NavigableMap<Integer, String> lineMap = new TreeMap<>();
        while (input.hasNextLine()) {
            addLine(lineMap, input.nextLine());
        }
        printLongestLines(lineMap, numberOfLinesToPrint);
    }

    private static void printLongestLines(NavigableMap<Integer, String> lineMap, int numberOfLinesToPrint) {
        for (int i = 0; i < numberOfLinesToPrint; i++) {
            System.out.println(lineMap.pollLastEntry().getValue());
        }
    }

    private static void addLine(NavigableMap<Integer, String> lineMap, String line) {
        lineMap.put(line.length(), line);
    }
}

I thought about implementing a data structure based on the size of the input that would sort itself right after adding an input -- if the input was a valid addition, but then I remembered TreeMap and thought why reinvent the wheel? This works, but I'm curious if I've misjudged and the alternative would've been more efficient.

Remember to close resources
You are opening a file with
Scanner input = new Scanner(new File(args[0]));

but you are never closing the Scanner. This can lead to resource leaks and hard to track down bugs. This is typically solved by using a try-with-resources construct:
try (Scanner input = new Scanner(new File(args[0]))) {
    // ...
}

With this change, the Scanner will be opened at the beginning of the block, and always closed, automatically, at the end. This ensures that, whatever happens in the try block (exception or not), the resource will be properly closed.
Use of methods
Your code makes use of 2 methods:

printLongestLines, which is responsible for printing the top-most lines read.
addLine, which adds a line into a map.

The first method, printLongestLines, is great: its name is descriptive and does the job it is intended to do.
However, the second is awkward: it takes as parameter a map that it will modify. Generally, modifying input parameters inside a method is a bad practice. It means that the code isn't correctly decoupled. In this case, it is because this method is actually part of a bigger responsibility: storing the lines of the file inside a map. Conceptually, you want to break down the program into meaningful methods that perform a task; the task here is reading the file.
As such, consider the following method readLines instead:
private static NavigableMap<Integer, String> readLines(Scanner input) {
    NavigableMap<Integer, String> lineMap = new TreeMap<>();
    while (input.hasNextLine()) {
        String line = input.nextLine();
        lineMap.put(line.length(), line);
    }
    return lineMap;
}

The advantage is that reading from the Scanner and populating the line map is done inside a well defined method, that the main part of the code just invokes.
Iterators
The method printLongestLines is currently using pollLastEntry() to retrieve, and remove, the last entry of the map. This is a side-effect operation: this method is modifying the input map, by removing elements from it.
It would be preferable to use an Iterator to iterate over the map. Consider the following:
private static void printLongestLines(NavigableMap<Integer, String> lineMap, int numberOfLinesToPrint) {
    Iterator<String> iterator = lineMap.descendingMap().values().iterator();
    int i = 0;
    while (i < numberOfLinesToPrint && iterator.hasNext()) {
        System.out.println(iterator.next());
        i++;
    }
}

This gets the reversed map (with descendingMap) and iterates over the values only, since we're not interested in the key. It also highlights a potential bug in your current implementation: if you were to print a number of lines greater than the size of the map, it would fail. This is handled here by checking whether the iterator has a next element.
You don't need a map
You will notice that, in the map that was built, we're only interested in the values, i.e. the lines themselves. This shows that, in fact, we do not need a map. We can directly use a SortedSet where the String are sorted by their length.
private static SortedSet<String> readLines(Scanner input) {
    SortedSet<String> set = new TreeSet<>(Comparator.comparing(String::length, Comparator.reverseOrder()));
    while (input.hasNextLine()) {
        set.add(input.nextLine());
    }
    return set;
}

This creates a set that is sorted in reverse order using a comparator comparing their length. This is using Java 8 specific code (comparing and the method reference String::length) but the same can be done with anonymous classes.
With this change, you can have a very simple printLongestLines method:
private static void printLongestLines(SortedSet<String> set, int numberOfLinesToPrint) {
    set.stream().limit(numberOfLinesToPrint).forEach(System.out::println);
}

This is using the Stream API, but you could keep the same code as before for Java <= 7, using explicitely an iterator.

As oopexpert points out in a comment, you can also directly use a List<String> to store the lines of the file. Depending on the use-case, this also would have the advantage that duplicate lines are kept. The change to do in readLines would simply be to explicitely sort the list once the lines are read, with:
List<String> lines = new ArrayList<>();
// loop over input to add each line
lines.sort(Comparator.comparing(String::length).reversed());


Checking if file is within a directory for security I have a security manager I'm writing for a Java program, and within the checkRead method, I wish to only allow reads to files within a given directory.

The basis of it is that it will get a canonical file for the input (which is actually a string as per the method contract). It will then begin taking the file's parent repeatedly until it either matches one of the trusted directories, or becomes null (from trying to take the parent of the root directory). This check should be secure both on Unix/linux and Windows environments and styles of filenames. I don't need 100% certainty that a valid and allowed, but mangled or non-standard path would pass, but I certainly cannot rework the program's API to open files in a different, more secure manner, as my application's classloader needs to use this method to check its reads.

Are there any glaring issues (security or style) that anyone might see here?

File tested;
try {
    tested = new File(file).getCanonicalFile();
} catch (IOException e1) {
    throw new SecurityException(
            "The basedir resolution failed to resolve.");
}

File parentFile = tested;
while (parentFile != null) {
    if (basedir.equals(parentFile) || classDir.equals(parentFile)) {
        return;
    }
    parentFile = parentFile.getParentFile();
}
logger.warn("MosstestSecurityManager stopped an attempt to read a file from non-core code"
        + file);

throw new SecurityException(
        "MosstestSecurityManager stopped an attempt to read a file from non-core code");

Nit-Picks

This exception-handling code should include the IOException as part of the SecurityException re-throw:

try {
    tested = new File(file).getCanonicalFile();
} catch (IOException e1) {
    // set the cause of the SecurityException so that users can potentially fix things
    throw new SecurityException(
            "The basedir resolution failed to resolve.", e1);
}

General

I believe the rest of the code supplies the required functionality. There are odd cases where, for example, on Linux you can remount a sub-directory at a different mount point. These two distinct file-systems may mirror each other, and a file/directory in one mount-point is identical to the other mount point.

This may produce false-positives in your code (where your code will claim the directory is not allowed, but it actually is...). False-positives in 'edge cases' in a security situation are better than false-negatives.

The intricacies of the new-in-Java-7 NIO2 Path class/interface may help with this. You could translate your File instances in to Path instances, and then use the isSameFile(...) method... which may, or may not help (reading the documentation it is unclear, and I do not have direct experience with that).

Update .... more Paths:

Using the Path and other NIO2 features, your code could probably be reduced to:

// basePath is already resolved as a Path.realPath from basedir
// classPath is already resolved as a Path.realPath from classDir
Path filePath = file.topath().realpath();
if (!filePath.startsWith(basePath) || !filePath.startsWith(classPath) {
    // illegal file access....
    throw new SecurityException(.....);
}


Handle data received by Ajax request and update database (prepared statement) I have an Ajax request from a page where the user is being asked to enter their date of birth. The request URL file has the code below and works all good. However, I'll be rewriting all MySQL/MySQLi functions used on the same website and this is generally how I use prepared statements. Should I avoid using die();? Is the code below acceptable and secure at some level?

// If received the birthday of logged in user
if(isset($_REQUEST['new_dob']) && isset($_REQUEST['userId'])) {
  $newdob = $_REQUEST['new_dob'];
  $userid = $_REQUEST['userId'];

  $check_info = "SELECT date_of_birth FROM users WHERE id = ? ";
  $check_mate = $conn -> prepare($check_info);
  if ( false === $check_mate ) {
    die('prepare() failed: ' . htmlspecialchars($conn->error));
  }
  $check_mate -> bind_param("i", $userid);
  $check_exe = $check_mate -> execute();
  if ( false === $check_exe ) {
    //No dob record at all for this userid
    die('execute() failed: ' . htmlspecialchars($conn->error));

  } else {
    $check_mate -> bind_result($date_of_birth);
    $check_mate -> fetch();
    if ($newdob != $date_of_birth) {
        $update_flag = 1;
        $check_mate -> close();
    } else if ($newdob == $date_of_birth || $newdob == '--' || $newdob == '0000-00-00' || $newdob == false || $newdob == NULL) {
        exit;
    }
  }
  if($update_flag == 1) {
    $update_dob = "UPDATE users SET date_of_birth = ? WHERE id = ? ";
    $update_exe = $conn -> prepare($update_dob);
    if ( false === $update_exe ) {
      die('prepare() failed: ' . htmlspecialchars($conn->error));
    }
    $update_exe -> bind_param("si", $newdob, $userid);
    $update_result = $update_exe -> execute();
    if ( false === $update_result ) {
      //No record at all for this userid
      die('execute() failed: ' . htmlspecialchars($conn->error));
    } else {
        $updated = 1;
        $update_exe -> close();
    }
  } else {
    // set dialog as completed
  }
}

Should I avoid using die();?

I would (at least in the places you are using it). It makes your code really hard to reuse. And it can easily lead to problems once your requirements change.

Personally, I would just use exceptions, and let them bubble up to wherever you want to handle the problem (I usually follow MVC loosely and do this in the controller).

Security

Yes, your code should be secure. You are using prepared statements, and you are using them correctly. Additionally, you prevent XSS, which is also done correctly.

Two small things:

You should not echo database error messages directly to the enduser. It may contain information that can help in further attacks, and it is not very user friendly.
You should not use REQUEST, but POST instead. Requests that change state should always be submitted via POST, and using REQUEST thus provides a fall-back to GET, which might aid attackers in exploiting other existing vulnerabilities such as CSRF or XSS. Example: Let's say your request is vulnerable to CSRF. Without the fallback, I could only use POST, meaning I can only distribute my payload via websites I control or websites that allow JavaScript to be posted. But if you do allow the fallback to GET, now I can use any website where I can eg control image urls, which is easier to find. Same for XSS, where it's distributing links vs getting the victim to visit my website.

Readability

I found your code a bit hard to read, resulting from a combination of these issues:

Naming

don't shorten variable names. If I have to guess and/or remember what you meant, it will make the code harder to read. Examples: dob (date of birth?), mate (no idea), exe (execute)
consistency: Same things should be named the same, and all variable names should follow the same pattern. If you use snake_case, use it everywhere (eg newdob vs date_of_birth; one uses snake_case, one doesn't, one shortens dob, one doesn't; same with new_dob vs userId).
again naming consistency: Here, you use the same pattern for different things: update_exe/update_result vs update_dob. All three deal with dob stuff, but only the ar contains it in its name (instead of eg update_query which would follow the pattern of the other two names).
one more naming consistency issue: For the select query, you use this pattern: check_info (the query), check_mate (bind result for param as well as result, and check result), check_exe (execute result). For the update query, you use update_dob (the query), update_exe (not execute result, but prepare result, as well as bind result), update_result (execute result). It would be better to be consistent here.

Formatting

I wouldn't put spaces around ->. Spaces indicate an interaction of two entities (eg when using == or .), but that's not what's happening. There is only one entity, and its method is being called. This confused me a couple of times while reading your code.
inconsistent spacing, eg in your if statements.
inconsistent function use: you use exit and die interchangeably in very similar situations. I would pick one and stick with that.

Nested ifs and lack of function

For my taste, your code is too nested, and it does too many different things for its length. An alternative might look like this (a bit simplified):

$result = processBirthday($_POST['newBirthday'], $_POST['userId']);
[...]

function processBirthday($newBirthday, $userId) {
    if (!isValidDate($newBirthday)) {
        return "not valid";
    }

    $oldBirthday = getBirthday($userId);
    if ($newBirthday == $oldBirthday) {
        return "same date";
    }
    updateBirthday($newBirthday, $userId);
}

function isValidDate($newBirthday) {
    return !($newdob == '--' || $newdob == '0000-00-00' || $newdob == false || $newdob == NULL);
}

The getBirthday and updateBirthday functions now do the actual db interaction. This way, you can easily reuse those functions in other parts of your application, and your code is a lot more readable.

Other

double checks: if ($newdob != $date_of_birth) { ... } else if ($newdob == $date_of_birth) { ... } here you don't need the second check. Either it's the same, or it's not.
one-time variables. If these kinds of variables have good names they may sometimes increase the readability of code. But often times, they just make code harder to read. So instead of $update_result = $update_exe -> execute(); if ( false === $update_result ) I would just write if ( false === $update_exe->execute()) or just if (!$update_exe->execute()).


Printing numbers in lexicographic order I saw this problem posted as an interview question asked at Bloomberg:

  Given an integer N, print numbers from 1 to N in lexicographic order.
  Restriction. One cannot use strings or characters.

Below is my solution to this problem. Can the algorithm be improved?

#!/usr/bin/env python
import sys
import traceback

def printlexnum(i, tens, number):
    lexnum = i*tens
    for j in range(lexnum,min(number+1,lexnum+tens)):
        print j
    if number>=lexnum:
        printlexnum(i, tens*10, number)
    return

try:
    if len(sys.argv) < 2:
        number = 0
        while number < 0:
            number = int(raw_input('please enter number >0: '))
        if number == 0:
            sys.exit(1)
    else:
        number = int(sys.argv[1])
        if number <= 0:
            print "Bad argument." + number + " must be greater than zero."
            sys.exit(1)
    for i in range(1,min(10,number+1)):
        print i
        printlexnum(i,10, number)
except ValueError, e:
    traceback.print_exc()
    print sys.argv[1], " Input not an integer"
except Exception, e:
    traceback.print_exc()
    print sys.argv[1], " Exception thrown"
finally:
    a = 1 # dummy line

Okay, let me point out some stylistic things first:

Doing traceback.print_exc() in an except block feels somewhat odd. Either you hide the stack trace by printing your own error message—which is actually helpful to the end user—or you leave the exception as it is.
Exceptions should be caught locally near to the code which may raise them. So having a big try block with that many lines is not really a good idea. Especially when you are catching all exceptions in the end—you are just hiding stuff that could be totally your fault.
The finally is useless? If you want to do nothing in a block, then use pass; but in your case, you can just leave the finally block out.
For exceptions your program could actually recover from, you really should do exactly that. When the user gets prompted for a number and enters something else, give him an error but let them try again.
In regards to the previous point, you actually have some hint of letting the user try again, with the while number < 0:. However, if the user enters a non-number int() will throw a ValueError and the program will just exit.
Using sys.exit(1) is like shutting your computer down by plugging the cable. Provide a better way to shut down your program. Use the existing exception mechanism to shut it down.
if number == 0: sys.exit(1) — if you’re not accepting a zero either, why don’t you change the while loops condition to “lower or equals zero”?
printlexnum(i, 10, number) — if the second parameter is always a 10, why have it as a parameter?
return — No need to explicitely return from a function when that’s the last statement of the function and no value is specified.

Moving on to the algorithm:

The order is not correct. For example 100 is being sorted after 19, when it should be sorted after 10 (like 10 is sorted after 1).
The for-loop in the “main” program should really be handled by the algorithm too. There should be some high-level printlexnum(n) which just prints all numbers from 1 to n.

The easiest way to get a lexicographic order of numbers is when you sort their string representations because strings are always sorted lexicographically. You can actually do this in a single line:

print('\n'.join(sorted(map(str, range(1, number + 1)))))


Conditional AND statement- which is more readable? Does this function

automationStatusIsSuccessful = (data) ->
    data.Automation.Status isnt "FAILED" and data.Automation.Status isnt "COMPLETEDWITHERROR"`

make the conditional statement more readable or less readable?

With:

  automationStatusIsSuccessful = (data) ->
    data.Automation.Status isnt "FAILED" and data.Automation.Status isnt "COMPLETEDWITHERROR"

  checkIteration = (data) ->
    if iteration < Configuration.CHECK_ITERATIONS and automationStatusIsSuccessful(data)

Without:

checkIteration = (data) ->
  if iteration < Configuration.CHECK_ITERATIONS and data.Automation.Status isnt "FAILED" \
  and data.Automation.Status isnt "COMPLETEDWITHERROR"

I don't know coffeescript, but in general, extracting complex conditions to a helper function is a common refactoring technique. When you do that, you effectively give a name to the previously nameless condition, which works like documentation, and can naturally improve readability.

Another advantage is that such function would hide the details of the inner workings of determining whether the automation status was successful or not. So if later you want to change the underlying conditions, the place to do that will be well identified, in a dedicated function, rather than buried inside some other function.

Of course, this doesn't mean that you should extract every less-than-trivial boolean condition to a helper function. Where you draw the line may be different from person to person. The fact that you're asking this question seems to suggest that you're inclined to make this move. (Personally I would extract it too.)


Invalidate a JS Object when any of its values is null or empty I created a simple Javascript method to recursively parse a JS Object and find out if any of its values or sub values is set to null or is empty string.

I could't break on when using Array.map() or Array.forEach() so I went with this :

const isValidObject = (obj) => {
  let invalid = []
  const validate = (obj) => {
    Object.values(obj).map(el => {
      if (typeof el === 'object') {
        validate(el)
      } else if (el === null || el === '') {
        invalid.push(el)
      }
    })
    return invalid.length === 0
  }
  return validate(obj)
}

If you have any opinonated or objective thought about this way of doing, please share it with me.

const isValidObject = (obj) => {
  let invalid = []
  const validate = (obj) => {
    Object.values(obj).map(el => {
      if (typeof el === 'object') {
        validate(el)
      } else if (el === null || el === '') {
        invalid.push(el)
      }
    })
    return invalid.length === 0
  }
  return validate(obj)
}

let toto = {
 name: 'toto',
  age: 12,
  pony: {
    name: 'rainbow dash',
    age: ''
  }
}

console.log('test :', isValidObject(toto))

Say hello to your new friend, Array.prototype.every. You'll have a callback which actually returns false on any element which is null or ''. The .every call will be short-circuited and your iteration won't have to go over all the nested elements. No need for extraneous invalid array either.


Longest Valid Parentheses This is the "Longest Valid Parentheses" problem from leetcode.com:

  Given a string containing just the characters "(" and ")",
  find the length of the longest valid (well-formed) parentheses substring.
  For "(()", the longest valid parentheses substring is "()", which has length 2. Another example is ")()())", where the longest valid parentheses substring is "()()", which has length 4.

I was studied this interview question during mock-interview. And I was able to test it against the test cases.

Start from the longest length, and use a stack to identify if it is valid. If not, length - 1.

Put the elements index in the string into a stack, if "(" then add to the stack. If ")" if stack not empty, if s[stack.top()] == "(", stack.pop(), else stack.push(i). If stack is empty, stack.push(i).

The most important idea is that the substring between the adjacent indices in stack is valid.The most important aspect with dynamic programming is what the subscript j represent. Let longest be the array for dp. longest[i] is the longest substring end with i.

def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype:
        """
        if len(s) <= 1: return 0
        longest = [0] * len(s)
        max_len = 0
        for i in range(1, len(s)):
            if s[i] == ")":
                if s[i-1] == "(":
                    longest[i] = 2 + (longest[i-2] if i - 2>= 0 else 0)
                    print "hrere"
                    print longest[i]
                    if longest[i] > max_len: max_len = longest[i]
                else:
                    if i - longest[i-1] - 1 >= 0 and s[i-longest[i-1]-1] == "(":
                        longest[i] = 2 + longest[i-1] + (longest[i-longest[i-1]-2] if i-longest[i-1]-2 >= 0 else 0)
                        if longest[i] > max_len: max_len = longest[i]
        return max_len

1. Review

There are a couple of print statements that seem to be left over from a debugging session. If you want to trace the execution of a Python program, you can do so without editing the code, by using the Python debugger. This would avoid the risk of forgetting to remove your debugging code.
There is no need for the special case:

if len(s) <= 1: return 0

since these cases are handled correctly by the rest of the code.
There is also no need for the special case:

if s[i-1] == "(":

since if you look at the two branches you'll see that they do the same thing.
The algorithm is slightly tricky so I would like to have a comment explaining the values that we are going to put in the array longest:

# longest[i] will be length of longest valid substring ending at i.

The expression i - longest[i-1] - 1 appears in several places so would benefit from being stored in a variable:

# Index where matching ( would have to be, if it exists.
j = i - longest[i-1] - 1

The test i-longest[i-1]-2 >= 0 becomes j-1 >= 0 and this can be simplified to j > 0 to avoid the subtraction, and then just to j since you have already tested j >= 0.
We can avoid testing j at all by noting that if it is 0 then j-1 is -1 and longest[-1] is still a valid lookup, getting the last entry of the array longest, which is 0 as required.
The line:

if longest[i] > max_len: max_len = longest[i]

can be simplified using the built-in max:

max_len = max(max_len, longest[i])

Instead of maintaining a running maximum, just run max once at the end:

return max(longest, default=0)

This requires Python 3.4 or later, for the default argument. On earlier versions of Python you'd have to write something like:

return max(longest) if longest else 0

2. Revised code

# longest[i] will be length of longest valid substring ending at i.
longest = [0] * len(s)
for i in range(1, len(s)):
    if s[i] == ')':
        # Index where matching ( would have to be, if it exists.
        j = i - longest[i-1] - 1
        if j >= 0 and s[j] == '(':
            longest[i] = 1 + i - j + longest[j-1]
return max(longest, default=0)


VBA script to add formulas to Excel is running slow I have written the following VBA script that searches for a text string in column CI and if it finds it the specific text the script adds a formula to a series of cells. The script itself runs correctly but I think it is taking much longer to run than it should. I am assuming there are some form efficient ways to write the code.

I have other scripts in the same Excel workbook that take 30 seconds to run but this script takes almost 7 minutes. It is searching through just over 900 cells in the test case I am using. Which in the grand scheme of thing, that is not really that many cells. How can I make it more efficient?

Private Sub Material_Formulas()

Dim lRow As Integer
Dim tiesMaterial As String
Dim result As String

lRow = Sheets("Material").Range("A2").End(xlDown).Row
lCol = Sheets("Material").Range("A2").End(xlToRight).Column

'Starts the count at column CU
endCount = lCol - 1

    For c = 99 To endCount
        For r = 3 To lRow

        tiesMaterial = Cells(r, 87).Value

        'Looks to see if the cells starting at CU2 contains a number and then iterates through each cell in row 3 to add a formula
        If tiesMaterial = "TIES MATERIAL" Then

            materialID = Sheets("Material").Cells(r, "CQ").Address(False, False)
            materialYear = Sheets("Material").Cells(2, c).Address(False, False)

            'Starting in cell CU3 it adds the formula =INDEX(BOM_Summary_Array,MATCH(CQ3,BOM_Summary_ID,0),MATCH(CU2,BOM_Summary_Head,0))
            Sheets("Material").Cells(r, c).Formula = "=INDEX(BOM_Summary_Array,MATCH(Material!" & materialID & ",BOM_Summary_ID,0),MATCH(Material!" & materialYear & ",BOM_Summary_Head,0))"

        End If

        Next r
    Next c

End Sub

When working with Excel and writing to cells the most common performance issue come from the sheet being constantly updated in the background while the script is running. In order to gain more speed you should save the state of a few properties for as long as the script is running and restore their values when it finishes.

For example:

Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False

Reference: Excel VBA Performance Coding Best Practices


ball-game created in Python 3 This is a very simple ball game in which we have to avoid projectiles falling from the sky. This is my second project and first game. Please review and tell where I can improve.

import time
import random
import pygame
pygame.init()

#colors
black=(0,0,0)
white=(255,255,255)
red=(255,0,0)
green=(0,255,0)
blue=(0,0,255)
darkViolet=(148,0,211)

#display
displayWidth=1024
displayHeight=600
display=pygame.display.set_mode((displayWidth, displayHeight))
pygame.display.set_caption('PHY')
heart=pygame.image.load('heart.png')
myfont=pygame.font.SysFont('Terminal', 18)
clock=pygame.time.Clock()
endTime=time.time()

#physics
x,y=displayWidth/2,displayHeight/2
ux, uy, ax, ay= 0, 0, 0, 0 # u means velocity, a  means acceleration
yp1, up1, ap = 0, 50, 50 #p for projectile
xp1,yp1,up1,ap1=[],0,50,50 #projectile variables. xp1 list coz multiple projectiles
uc, ac = 20, 5 # c stands for the amount of change on key press
score, lives=0,3
touching=False
running=True

#misc
projectile=pygame.Surface((10,20))
projectile.fill(darkViolet)

#adding random locations for projectiles to spawn in
for _ in range(20):
    xp1.append(random.randint(0,displayWidth))

while running:
    #taking dt to be a small value which will depend on the processing power
    startTime=time.time()
    t=startTime-endTime

    #changing the postions and velocities with time
    ux+=ax*t
    uy+=ay*t
    x+=ux*t
    y+=uy*t
    up1+=ap*t
    yp1+=up1*t

    endTime=time.time()

    #checking for collision of ball with boundaries
    if x<0:
        x=0
        ux=-ux/3
    if x>displayWidth:
        x=displayWidth
        ux=-ux/3
    if y<0:
        y=0
        uy=-uy/3
    if y>displayHeight:
        y=displayHeight
        uy=-uy/3

    for ev in pygame.event.get():
        if ev.type == pygame.QUIT:
            running=False
        elif ev.type == pygame.KEYDOWN: #acts on pressing and not on holding key
            if ev.key == pygame.K_UP:
                ay-=ac
                uy-=uc
            if ev.key == pygame.K_DOWN:
                ay+=ac
                uy+=uc
            if ev.key == pygame.K_LEFT:
                ax-=ac
                ux-=uc
            if ev.key == pygame.K_RIGHT:
                ax+=ac
                ux+=uc
        elif ev.type == pygame.KEYUP:
            if ev.key == pygame.K_UP:
                ay=0
            if ev.key == pygame.K_DOWN:
                ay=0
            if ev.key == pygame.K_LEFT:
                ax=0
            if ev.key == pygame.K_RIGHT:
                ax=0

    #condition for when the projectile crosses the screen
    if yp1>displayHeight:
        yp1=0
        up1=3*up1/5
        ap+=5
        xp1=[]
        score+=1
        for _ in range(20):
            xp1.append(random.randint(0,displayWidth))

    #checking for collision between ball and projectile
    for g in range(20):
        if x>xp1[g]-10 and x<10+xp1[g] and y>yp1-15 and y<yp1+15:
            touching=True
            xp1[g]=1050
    if touching:
        if lives>1:
            lives-=1
            touching=False
        else:
            running=False

    #displaying
    display.fill(black)
    for g in range(lives): #displaying the lives as hearts
        display.blit(heart, (950+g*25,25))
    for g in range(20): #displaying the same projectile at 20 places
        display.blit(projectile, (xp1[g], yp1))
    textDisp=myfont.render('SCORE: %s'%(score),False,white)
    pygame.draw.circle(display, red, (int(x),int(y)), 10, 0) #displaying the ball
    display.blit(textDisp,(950,50)) #displaying the score
    pygame.display.update()
    clock.tick(60)

pygame.quit()
quit()

Follow standard identifier conventions.  Variable are lower_case, class names should be CamelCase, and constants should be UPPER_CASE.  With this in mind, your block of colours at the start should be altered:

# Colours
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
#... etc ...

Named colours are fine, but what are you using them for?  Maybe, after naming colours, name some of the usages, and assign the named colours.

BALL_COLOUR = RED
SCORE_COLOUR = WHITE

Note the spacing above.

ux+=ax*t
uy+=ay*t
x+=ux*t
y+=uy*t

... I find hard to read.  Add a space before and after operators, a space after commas, etc.

ux += ax * t
uy += ay * t
x += ux * t
y += uy * t

... is much easier to read.

score, lives=0,3

Tuple unpacking assignment is a wonderful feature.  But don’t use it for unrelated values, like score and lives.  Use two separate assignment statements. But when you do use it, remember spaces around the equals, and after the commas.

Declare variables as close as possible to where you use them.  What is this running = True statement, near the start?  Is there someone walking and running as well as bouncing a ball?

running = True
while running:
     # ...

This is much clearer.  The value controls the loop.

Watch for “if condition, do something, else if different condition, do same thing”.  Use an “or” in the test.

if ev.key == pygame.K_UP or ev.key == pygame.K_DOWN:
    ay = 0

Don’t intermix unrelated code.

textDisp = ...
pygame.draw.circle(...)
display.blit(textDisp, ...)

Keep the two textDisp lines together; the circle draw code is unrelated and should be moved before or after this code.

Elephant in the room:  Variable names. They are terrible.  I’d suggest better ones, but I’d suggest using classes for player/projectile even more.  And maybe a function or two for organization. But as this is your third project, I don’t want to confuse you with constructs you may not have learned yet.

Let us know what you know, and perhaps we can help further.

Inefficiency: repeating the same test 20 times.  Both y and yp1 remain constant in this loop:

for g in range(20):
    if x>xp1[g]-10 and x<10+xp1[g] and y>yp1-15 and y<yp1+15:

Instead, check for a y-collision first, and only if it is a possibility, then check the 20 x-collisions.

if y > yp1 - 15  and  y < yp1 + 15:
    # loop over all xp1 values

Hard-coded numbers. You repeat 20 multiple times throughout the code.  What if you want to change that?  Find every place it is used and change it?  Better: use a variable for num_projectiles.  Even better, just iterate over the storage structure itself:

if y > yp1 - 15  and  y < yp1 + 15:
    for xp in xp1:
        if x > xp - 10  and  x < xp + 10:
            # collision code


Random MP3 Selector and Player So, I am either a glutton for punishment, or I have no life, but I wrote a script to answer a question over on Ask Ubuntu as a solution for selecting a random MP3 file in a given directory, and playing it in the specified player of choice.  I am half-embarrassed to share this because I know it's not my best work and relies on user input for pretty much anything.

The script is designed to be passed the executable name for the media player the user wants to use, and select a random MP3 file to play in that player.  There is a small level of Evil in here, because the person executing this script must specify a media player.  It also assumes it's in the user's /home/$USER/Music directory on Linux-based systems, so to use another dir it has to be specified.

Any improvements you want to give me, feel free.  I know this works, though.  Main concerns are if I derped anywhere and did a bad thing.

randommp3.py (or, in a Gist if you want pretty):

#!/usr/bin/python

import getpass
import subprocess as sp
import os
import glob
import random
import argparse

if __name__ == "__main__":
    # Parse arguments to the script
    argparser = argparse.ArgumentParser(description="Open a random MP3 in the player of choice, or the default player",
                                        add_help=True)
    argparser.add_argument('--dir', '--directory', '--music-dir', dest='dirpath', type=str,
                           default=str('/home/' + getpass.getuser() + '/Music'), required=False,
                           help="The path to the directory where your music is stored. If the path has spaces, wrap the "
                                "entire path in single-quotes ('/home/ubuntu/My Music/' for example). If not specified, "
                                "the current user's Music directory in their /home/ folder is used.")
    argparser.add_argument('player', type=str, help="The executable name of the media player "
                                                    "to open the MP3 with. If none specified, "
                                                    "uses the system default player.")

    # Using the above 'argparser' items, get the arguments for what we're going to be using.
    args = argparser.parse_args()

    # Gp to the directory your music is in.
    os.chdir(args.dirpath)
    mp3s = glob.glob('*.mp3')

    # Modify the directory path to make sure we have the trailing slash
    dirpath = args.dirpath
    if dirpath[-1] not in '/\\':
        dirpath += '/'

    # Actually open the MP3 file, and /dev/null to suppress output messages from the process.
    DEV_NULL = open(os.devnull, 'w')
    execpath = [args.player, '%s%s' % (dirpath, str(random.choice(mp3s)))]
    sp.Popen(execpath, stdout=DEV_NULL, stderr=DEV_NULL)

I would improve the following things:

move the parsing argument part into a separate function (extract method)
define descriptions and helps in multiline string constants
use os.path.join() to join the path components - would also help to avoid worrying about a trailing slash
order imports alphabetically (PEP8 reference)

The improved code:

#!/usr/bin/python
import argparse
import getpass
import glob
import os
import random
import subprocess as sp

DESCRIPTION = "Open a random MP3 in the player of choice, or the default player"
DIRECTORY_ARGUMENT_HELP = """
The path to the directory where your music is stored.
If the path has spaces, wrap the entire path in single-quotes ('/home/ubuntu/My Music/' for example).
If not specified, the current user's Music directory in their /home/ folder is used.
"""
PLAYER_ARGUMENT_HELP = """
The executable name of the media player to open the MP3 with.
If none specified, uses the system default player.
"""

def parse_args():
    """Parses command-line arguments and returns argparse arguments."""
    user_home_directory = os.path.join('/home', getpass.getuser())
    default_music_directory = os.path.join(user_home_directory, 'Music')

    parser = argparse.ArgumentParser(description=DESCRIPTION, add_help=True)
    parser.add_argument('--dir', '--directory', '--music-dir',
                        dest='dirpath', type=str, default=default_music_directory, required=False,
                        help=DIRECTORY_ARGUMENT_HELP)
    parser.add_argument('player', type=str, help=PLAYER_ARGUMENT_HELP)
    return parser.parse_args()

if __name__ == "__main__":
    args = parse_args()

    # Go to the directory your music is in.
    os.chdir(args.dirpath)
    mp3s = glob.glob('*.mp3')

    # Actually open the MP3 file, and /dev/null to suppress output messages from the process.
    DEV_NULL = open(os.devnull, 'w')
    execpath = [args.player, os.path.join(args.dirpath, random.choice(mp3s))]
    sp.Popen(execpath, stdout=DEV_NULL, stderr=DEV_NULL)

Note that if you would have been on Python 3.x, the DEVNULL could have been imported from the subprocess module:

from subprocess import DEVNULL


Replacing each letter with the letter that is in the corresponding position from the end of the English alphabet I wrote a small program for hyperskill/jetbrains academy to encrypt the message "we found a treasure!" and print only the ciphertext (in lower case) by replacing each letter with the letter that is in the corresponding position from the end of the English alphabet (a→z, b→y, c→x, ... x→c, y →b, z→a) and without replace spaces or the exclamation mark.

I would like code review comments in terms of correct use of java.

package encryptdecrypt;

public class Main {

    final static int lower_case_a = 'a';
    final static int lower_case_z = 'z';

    public static void main(String[] args) {
        String s = "we found a treasure!";

        StringBuffer reverse = new StringBuffer();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if ((int)c >= lower_case_a && (int)c <= lower_case_z)
                reverse.append((char)(lower_case_z - c + lower_case_a));
            else
                reverse.append((char) c);
        }
        System.out.println(reverse.toString());
    }
 }

With

final static int lower_case_a = 'a';
final static int lower_case_z = 'z';

While it's arguably good that you have 'a' and 'z' stored as variables and not floating around, I don't think they're named well. lower_case_a tells you exactly as much as 'a' itself, so you aren't really gaining much. The purpose of the variable would make for a better name. Also, since those are constants, they should be upper case, and underscore-separated. I'd change those lines to:

final static int ALPHABET_LOWER_BOUND = 'a';
final static int ALPHABET_UPPER_BOUND = 'z';

Also, as mentioned in the above link, Java uses camelCase, not snake_case.

if ((int)c >= lower_case_a && (int)c <= lower_case_z)
    reverse.append((char)(lower_case_z - c + lower_case_a));
else
    reverse.append((char) c);

This has a few notable things:

Do not omit braces here. I won't go as far as to say that they should never be omitted, but the cases where it's appropriate to not use them are pretty slim. If you ever make changes to those lines and don't notice that you didn't use braces, at best you'll need to deal with syntax errors, and at worst you'll get weird behavior that you'll need to debug. Just use them. It costs next to nothing and prevents a range of errors.
Instead of writing (int)c in a few places, I'd probably instead save that in a variable.
(char) c isn't necessary. c is already a char.
You could use a ternary since each branch is just giving its data to append.

Something closer to:

int code = c;
char newChar = (code >= ALPHABET_LOWER_BOUND && code <= ALPHABET_UPPER_BOUND)
                 ? (ALPHABET_UPPER_BOUND - c + ALPHABET_LOWER_BOUND) : c;

reverse.append(newChar);

Although whether you'd want to use a ternary here is subjective. That line is a little long.

I also agree with @dariosicily though. You never use i for anything other than indexing, so you might as well just use a foreach loop and iterate the string directly.