Download image links posted to reddit.com This is a Python script to save imgur pictures posted to reddit.com forums. I'm looking for an assessment on the design of this script and any web security issues that might exist.

Obvious shortcomings: it only downloads image links http://i.imgur.com/xx.png not images from imgur pages http://imgur.com/page/ and lacks the ability to get image albums.

# purpose:   downloads images from imgur.com links posted to specified reddits
# platform:  python 3.2
# references:
#  - reddit JSON -- https://github.com/reddit/reddit/wiki/API:-info.json

import json
import urllib.request
import os, sys

def downloadPostsFrom(subreddit):
    "Returns reddit posts as JSON"
    try:
        f = urllib.request.urlopen("http://www.reddit.com/r/"+subreddit+"/.json");
        return json.loads(f.read().decode("utf-8"))["data"]["children"]
    except Exception:
        print("ERROR: malformed JSON response from reddit.com")
        raise ValueError

def parseImageURL_From(posts):
    "Returns tuple iterator (url, title)"
    for node in posts:
        post = node['data']
        # only accept links from imgur.com
        if post['domain'].endswith('imgur.com'):
            yield post["url"], post["title"]

def makeFileExt(content_type):
    "Return extension for specified content type"
    return {
        'image/bmp':'bmp',
        'image/gif':'gif',
        'image/jpeg':'jpg',
        'image/png':'png',
        'image/tiff':'tif',
        'image/x-icon':'ico'
        }.get(content_type, 'txt')

def makeFileName(title):
    "Compute valid file name from image title. Return file name or default.ext"
    title = title.strip(' .?:')
    file_name = title.translate(''.maketrans('\/:*?"<>|$@ ï»¿.','__.-_____S0___'))
    file_name = file_name.strip('_').replace('__','_').lower()
    return file_name + '.' if file_name else 'default.'

def makeSaveDir(save_dir):
    "Creates directory. Returns a valid directory name."
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    return save_dir + '/'

def downloadImagesIntoDir(save_dir, image_refs):
    "Download image files into specified directory."
    save_dir = makeSaveDir(save_dir)
    print('saving to:', save_dir)

    for url, title in image_refs:
        try:
            # open connection to image
            request = urllib.request.urlopen(url)
            if request.code == 200:
                content_type = request.headers.get_content_type()
                # filter in images
                if 'image' == content_type.split('/')[0]:
                    file_name = save_dir \
                            + makeFileName(title) + makeFileExt(content_type)
                    # download image to local file
                    print('  downloading:', title)
                    with open(file_name, "wb") as image_file:
                        image_file.write(request.read())
        except Exception:
            print("ERROR: bad request --", title)

def downloadRedditImages(subreddits):
    "Download imgur images from reddit. Returns None."
    for subreddit in subreddits:
        try:
            # reddit_posts: JSON
            reddit_posts = downloadPostsFrom(subreddit)
            image_urls = parseImageURL_From(reddit_posts)
            downloadImagesIntoDir(subreddit, image_urls)
        except Exception:
            pass

def main():
    "Use app as console program."
    if len(sys.argv) > 1:
        downloadRedditImages(sys.argv[1:]);
    else:
        # specify your default reddits here
        downloadRedditImages(['funny']);

if __name__ == '__main__':
    main()

Never do except Exception:, especially not to pass. You probably want to be catching KeyErrors specifically, or using dict.get in the first case, and in the other cases adjust accordingly.
There's no need to do json.loads(file_like_object.read()), just use json.load(file_like_object).
You can eliminate a race condition in makeSavedir by not calling os.path.exists, just call os.makedirs (and catch the IOError if you'd like to not raise the exception [and make sure to check its errno]).
You can use string formatting in place of adding strings.
Your try blocks are too big. They will catch various exceptions that you aren't handling. This is another instance of my first point.

There are other things, these were just the quick things from reading top to bottom :).

P.S. There's an unofficial Python wrapper for the reddit API at https://github.com/praw-dev/praw that you could consider using.


Find minimum number of rooms required Problem statement is as follows

  Given an array of time intervals (start, end) for classroom lectures (possibly overlapping), find the minimum number of rooms required.

  For example, given [(30, 75), (0, 50), (60, 150)], you should return 2.

This is supposed to be an easy challenge but it was not the case for me.

Here is my solution in JavaScript

// Given an array of time intervals (start, end) for classroom lectures (possibly overlapping),
// find the minimum number of rooms required.
// For example, given [(30, 75), (0, 50), (60, 150)], you should return 2.
exports.roomsRequired = function roomsRequired(lectureIntervals) {
    function Room() {return {busy: []};}

    let rooms = [];
    lectureIntervals.forEach(lectureInterval => {
        let roomFound = false;
        rooms.forEach(room => {
            let roomBusyInLectureHours = false;
            room.busy.forEach(reserved => {
                if (lectureInterval[0] > reserved[0] && lectureInterval[0] < reserved[1]) roomBusyInLectureHours = true;
                if (lectureInterval[1] > reserved[0] && lectureInterval[1] < reserved[1]) roomBusyInLectureHours = true;
                if (reserved[0] > lectureInterval[0] && reserved[0] < lectureInterval[1]) roomBusyInLectureHours = true;
                if (reserved[1] > lectureInterval[0] && reserved[1] < lectureInterval[1]) roomBusyInLectureHours = true;
            });
            if (!roomBusyInLectureHours) {
                room.busy.push(lectureInterval);
                roomFound = true;
            }
        });
        if (!roomFound) {
            let room = new Room();
            room.busy.push(lectureInterval);
            rooms.push(room);
        }
    });
    return rooms;
};

The only test case I have so far

let rooms = exports.roomsRequired([[30, 75], [0, 50], [60, 150]]);
for (let i = 0; i < rooms.length; i++) {
    console.log(rooms[i].busy)
}

Which prints

[ [ 30, 75 ] ]
[ [ 0, 50 ], [ 60, 150 ] ]

I am aware that I am not returning the number of rooms, but that is essentially the number of rows seen, so for example in the case above it is 2 as expected.

My question is, can this code be much shorter? I suspect I am missing something obvious being this challenge easy.

Pseudo code of my implementation would be something like this

For Each Interval:
    For Each Room in Rooms:
        For Each IntervalWithinThatRoom:
            Check If IntervalWithinThatRoom overlaps with Interval
        If No Overlaps Found
            Push Interval to Room
    If Interval Not pushed to any Room
        Create new Room
        Push Interval to Room
        Push new Room to Rooms

Edit - Unit Tests I have

expect(roomsRequired.roomsRequired([[30, 75], [0, 50], [60, 150]]).length).eq(2);
expect(roomsRequired.roomsRequired([[5, 7], [0, 9], [5, 9]]).length).eq(3);

I know that my approach may not add much value, but I would like to share it with you.

Detecting room hours overlapping with this logic is correct, but it is hard to read and understand:-

if (lectureInterval[0] > reserved[0] && lectureInterval[0] < reserved[1]) roomBusyInLectureHours = true;
if (lectureInterval[1] > reserved[0] && lectureInterval[1] < reserved[1]) roomBusyInLectureHours = true;
if (reserved[0] > lectureInterval[0] && reserved[0] < lectureInterval[1]) roomBusyInLectureHours = true;
if (reserved[1] > lectureInterval[0] && reserved[1] < lectureInterval[1]) roomBusyInLectureHours = true;

I think following the approach below will make it more readable and understandable:-

let [reservedStart, reservedEnd] = reserved, [lectureStart, lectureEnd] = lectureInterval;
let busyHours = [...new Array(reservedEnd - reservedStart)].map((v, i)=> reservedStart+i);
let lectureHours = [...new Array(lectureEnd - lectureStart)].map((v, i)=> lectureStart+i);
roomBusyInLectureHours = busyHours.filter(hour => lectureHours.includes(hour)).length > 0;


PRBHA-10: A hashing algorithm in Python So I've been working on a simple little hashing algorithm for Python that I like to call PRBHA-10 for short, or Pseudo-Random-Based Hash Algorithm. This is a hash algorithm in Python that is meant to be simplistic and secure. As you could see from the title, the algorithm implements a system with seeding the pseudo-random number generator to be able to produce the correct integer values when provided the correct password, therefore enabling the decryption of an encrypted byte sequence or string.

Here's the advantages of my method:

The functions are tiny and simple, unlike some hashing methods out there.
Despite the simplicity of the algorithm, it is secure due to the generation of large random numbers that scale with the password size.
There is no chance of revealing even part of the encrypted string without the full password due to the huge numbers created by the seeded PRNG and multiplication that completely messes up the string if the wrong password is entered.
It is fast. I have not done timeits yet, but the functions run in a trivial amount of time to generate their results.

The disadvantages:

A somewhat large password is required to ensure security - usually anything over seven characters is completely cryptographically secure.
It is vulnerable to the same brute-force attacks that any cryptographic encryption method is vulnerable to.
With larger passwords comes greater security, but also a larger hash. The hash size slightly increases with each character added onto the password.

Here's the whole module program, prhba.py:

"""Pseudo-Random Based Hash Algorithm (PRHBA-10) is a simple
Python cipher that uses the integer representation of a
string, along with taking advantage of the built-in
pseudo-random number generator to be able to securely encrypt
strings and bytearrays.

The algorithm uses the integer representation of byte sequences,
seeding the random number generator using the password to
create a predictable random number for later use, and a special
encoded form to turn any byte sequence into an ASCII string
using only the letters 'aceilnorst'. This is secure due to the
extremely large random number generated ensuring the security
of the result.

The result can be later decrypted using a special algorithm to
decipher the text into a large integer number. Then, the
password is used as a seed to once again get the random number
used earlier in the process. That integer is used to modify
the large integer to be able to get the integer form of the
original string, which can then be converted to a string.

This cipher currently only works in Python due to the specific
random number generation implementation in the `random` module.
"""

import math
import random

__all__ = ["encrypt", "decrypt"]

LETTERS = "aceilnorst"

def to_num(s):
  return int.from_bytes(s.encode(), 'little')

def from_num(n):
  return n.to_bytes(math.ceil(n.bit_length() / 8), 'little')

def encrypt(data, password):
  assert len(password) > 1, "Password length cannot be less than two"
  random.seed(to_num(password))
  unique_id = to_num(data) * random.getrandbits(len(password))
  chunk = []
  for digit in str(unique_id):
    chunk.append(LETTERS[int(digit)])
  return "".join(chunk)

def decrypt(encrypted_data, password):
  random.seed(to_num(password))
  partnum_digits = []
  for char in encrypted_data:
    partnum_digits.append(str(LETTERS.index(char)))
  partnum = int("".join(partnum_digits))
  return from_num(partnum // random.getrandbits(len(password)))

Here's the questions I have:

Is it PEP-8 compliant?
Are the variable names confusing?
Is there any parts that could be improved or further reduced?
Do you have any other suggestions?

Thanks in advance!

Don’t roll your own encryption.  It takes a team of experts to develop new secure encryption methods, and even they can get it wrong from time to time.

Huge hole in your DIY encryption:

If I use a 2-character password, I might naïvely expect I’d have \$62^2\$ possible passwords that I can encrypt the data with.  I’d be really shocked when it turns out there are only 4.

random.getrandbits(len(password))

generates 2 random bits, for \$2^2\$ possible values to multiply to_num(data) by.  Only 4 possibilities is a lot easier to attack than \$62^2\$ different possibilities!

And one of those possibilities ... all bits zero ... destroys all the data you want to encode.  So we’re down to actually only 3 possible numbers to test to reverse the encryption.

Any encryption mechanism worth its salt uses a salt (initial random data) to prevent the same message with the same password from being encrypted as the same text.

Code improvements: use generator expressions.  Eg)

chunk = []
for digit in str(unique_id):
    chunk.append(LETTERS[int(digit)])
return "".join(chunk)

would be more efficient rewritten as:

return "".join(LETTERS[int(digit)] for digit in str(unique_id))

The chunk list is never created in memory; instead, the join method pulls items one at a time from the generator expression.

Finally, don’t roll your own encryption.


Normalizing data in Excel table column with multiple values I have a table in excel which has 11 columns and 50,000 rows of data.

One of the columns contains email addresses and in some instances multiple addresses, separated with a ; character. Eg. a cell in that column might look like a@gmail.com;b@gmail.com;x@gmail.com .

In those instances where I have multiple addresses, I need to delete the row with the multiple addresses and create new rows in the table with each one of those addresses, also copying and pasting the rest of the columns.

An example of how originally the data might look like and how it should look like after processing:

Before:

After:

In order to accomplish that I wrote this piece of code:

Sub Fix_Table()
i = 1
table_size = Range("Table1").Rows.Count
'Goes through Table1 in "To" column and fixes the recipients
Do While i <= table_size

   cell_value = Range("Table1[To]")(i)

   If InStr(Range("Table1[To]")(i), ";") Then
        from_table = Range("Table1[From]")(i)
        subject_table = Range("Table1[Subject]")(i)
        receivedDate_table = Range("Table1[Received_Date]")(i)
        infolder_table = Range("Table1[In_Folder]")(i)
        size_table = Range("Table1[Size]")(i)
        weekday_table = Range("Table1[Weekday]")(i)
        date_table = Range("Table1[Date]")(i)
        month_table = Range("Table1[Month]")(i)
        year_table = Range("Table1[Year]")(i)
        time_table = Range("Table1[Time]")(i)
        inout_table = Range("Table1[In/out]")(i)

        recipients_table = Split(cell_value, ";")
        number_of_recipients = UBound(recipients_table, 1) - LBound(recipients_table, 1)
        Range("Table1[To]")(i).EntireRow.Delete

        For k = 1 To number_of_recipients + 1
            Range("Table1[To]")(i).EntireRow.Insert
            Range("Table1[From]")(i) = from_table
            Range("Table1[Subject]")(i) = subject_table
            Range("Table1[Received_Date]")(i) = receivedDate_table
            Range("Table1[In_Folder]")(i) = infolder_table
            Range("Table1[Size]")(i) = size_table
            Range("Table1[Weekday]")(i) = weekday_table
            Range("Table1[Date]")(i) = date_table
            Range("Table1[Month]")(i) = month_table
            Range("Table1[Year]")(i) = year_table
            Range("Table1[Time]")(i) = time_table
            Range("Table1[In/out]")(i) = inout_table
            Range("Table1[To]")(i) = recipients_table(k - 1)
            i = i + 1
            table_size = table_size + 1
        Next k

   Else
        i = i + 1
   End If

Loop
End Sub

The above code works , however it is extremely slow! Is there any faster way that I could do that for that size of data?

Ok, so this ended up being a little bit longer/more complicated than I hoped. I will do my best to explain so that you can follow along. Please ask questions if you get lost or confused!
Code first, then explanations:
Option Explicit

Private Type TRecord
    To As String
    From As String
    Subject As String
    ReceivedDate As Date
    InFolder As String
    Size As String
    Weekday As String
    RecordDate As Date
    Month As String
    Year As String
    Time As String
    InOut As String
End Type

Sub New_Fix_Table()
    ' Be sure to add 'Option Explicit' at the top of your modules. This prevents undeclared variables from slipping through.

    ' Never use underscores in names. They have special meaning to the interpreter.
    ' table_size = Range("Table1").Rows.Count

    ' ## Not Needed due to UBound/LBound ##
    ' Dim tableSize As Long
    ' Be sure to also properly qualify you range references.
    ' TableSize = ActiveWorkbook.Range("Table1").Rows.Count - Without proper qualification, your Range is really ActiveWorkbook.Range
    ' tableSize = ThisWorkbook.Range("Table1").Rows.Count
    ' ## ##

    'Goes through Table1 in "To" column and fixes the recipients

    Dim i As Long

    ' For loops such as these, I prefer for loops
    ' Do While i <= table_size

    ' I strongly prefer arrays for this purpose. If it was my own project, I even would use classes, but one step at a time for now.

    ' Change this to point to the correct worksheet.
    Dim inputSheet As Worksheet
    Set inputSheet = ThisWorkbook.Worksheets("TargetSheet")

    ' If your data is in a table, then you can use this method instead of referring to the range.
    Dim tableData As Variant
    tableData = inputSheet.ListObjects(1).Range.value

    ' Now, here is a trick I use when processing table data in a much more efficient manner.
    ' This does require a reference to Microsoft Scripting Runtime
    Dim headerIndices As Scripting.Dictionary
    Set headerIndices = GetHeaderIndices(tableData)

    ' Now we have a dictionary where we can use a key and return the index position of that key

    ' This is where it gets a little bit tricky. If we encounter a row with multiple emails, we need to duplicate the records.
    ' Otherwise, we want to keep the records as is. For this task, collections to the rescue!

    ' Having declared a Record Type, I can now use the Type as a container for my data (without needing a class)
    Dim record As TRecord

    ' The records collection will contain the created records
    Dim records As Collection
    Set records = New Collection

    Dim i As Long
    ' We loop through arrays using LBound and Ubound (lower bound, upper bound). The '1' denotes rows, whereas '2' would denote columns.
    ' I add 1 to the lower bound so I can skip the header row.
    For i = LBound(tableData, 1) + 1 To UBound(tableData, 1)
        ' Set all the properties of the record.
        record.From = tableData(i, headerIndices("From"))
        record.Subject = tableData(i, headerIndices("Subject"))
        record.ReceivedDate = tableData(i, headerIndices("Received_Date"))
        record.InFolder = tableData(i, headerIndices("In_Folder"))
        record.Size = tableData(i, headerIndices("Size"))
        record.Weekday = tableData(i, headerIndices("Weekday"))
        record.RecordDate = tableData(i, headerIndices("Date"))
        record.Month = tableData(i, headerIndices("Month"))
        record.Year = tableData(i, headerIndices("Year"))
        record.Time = tableData(i, headerIndices("Time"))
        record.InOut = tableData(i, headerIndices("In/out"))

        ' Split the addresses. If there are multiple addresses we dont need to rewrite the record, we just need to adjust the To field.
        Dim splitAddresses As Variant
        If InStr(tableData(i, headerIndices("To")), ";") > 0 Then
            splitAddresses = Split(tableData(i, headerIndices("To")), ";")

            Dim j As Long
            For j = LBound(splitAddresses) To UBound(splitAddresses)
                If Len(splitAddresses(i)) > 1 Then
                    record.To = splitAddresses(i)
                    records.Add record
                End If
            Next
        Else
            record.To = tableData(i, headerIndices("To"))
            records.Add record
        End If
    Next

    ' Now we have a colleciton of all of the records we need. Now, we need to translate those back into an array.
    Dim outputData As Variant

    ' The row is 0 based so we can add headers, but the headerIndices dictionary is already 1-based, so we leave the columns 1 based.
    ' Admittedly, I would avoid a mis-match of bases for re-dimming an array, I am only doing it this way to prevent confusion.
    ReDim outputData(0 To records.Count, 1 To headerIndices.Count)

    ' An array with the same base-dimensions would be one of the two following:
    ' ReDim outputData(0 To records.Count, 0 To headerIndices.Count - 1)
    ' ReDim outputData(1 To records.Count + 1, 1 To headerIndices.Count)
    ' You would then need to adjust the actual filling of the array as well.

    i = LBound(outputData, 2)

    Dim header As Variant
    ' Loop through all of the stored headers
    For Each header In headerIndices.Keys
        ' The LBound here dynamically points to the header row.
        outputData(LBound(outputData, 1), i) = header
    Next

    ' This way we can dynamically fill in the array.
    Set headerIndices = GetHeaderIndices(outputData)

    i = LBound(outputData, 2) + 1
    For Each record In records
        outputData(i, headerIndices("To")) = record.To
        outputData(i, headerIndices("From")) = record.From
        outputData(i, headerIndices("Subject")) = record.Subject
        outputData(i, headerIndices("Received_Date")) = record.ReceivedDate
        outputData(i, headerIndices("In_Folder")) = record.InFolder
        outputData(i, headerIndices("Size")) = record.Size
        outputData(i, headerIndices("Weekday")) = record.Weekday
        outputData(i, headerIndices("Date")) = record.RecordDate
        outputData(i, headerIndices("Month")) = record.Month
        outputData(i, headerIndices("Year")) = record.Year
        outputData(i, headerIndices("Time")) = record.Time
        outputData(i, headerIndices("In/out")) = record.InOut
    Next

    ' Now we just have to put the output data somewhere. Let's reuse the sheet we pulled from.
    OutputArray outputData, inputSheet, "Output_Data"
End Sub

Public Function GetHeaderIndices(ByVal InputData As Variant) As Scripting.Dictionary
    If IsEmpty(InputData) Then Exit Function

    Dim headerIndices As Scripting.Dictionary
    Set headerIndices = New Scripting.Dictionary

    headerIndices.CompareMode = TextCompare

    Dim i As Long
    For i = LBound(InputData, 2) To UBound(InputData, 2)
        If Not headerIndices.Exists(Trim(InputData(LBound(InputData, 1), i))) Then _
           headerIndices.Add Trim(InputData(LBound(InputData, 1), i)), i
    Next

    Set GetHeaderIndices = headerIndices
End Function

Public Sub OutputArray(ByVal InputArray As Variant, ByVal InputWorksheet As Worksheet, ByVal TableName As String)
    Dim AddLengthH As Long
    Dim AddLengthW As Long

    If NumberOfArrayDimensions(InputArray) = 2 Then
        If LBound(InputArray, 1) = 0 Then AddLengthH = 1
        If LBound(InputArray, 2) = 0 Then AddLengthW = 1

        Dim r As Range
        If Not InputWorksheet Is Nothing Then
            With InputWorksheet
                .Cells.Clear
                Set r = .Range("A1").Resize(UBound(InputArray, 1) + AddLengthH, UBound(InputArray, 2) + AddLengthW)
                r.value = InputArray
                .ListObjects.Add(xlSrcRange, r, , xlYes).Name = TableName

                With .ListObjects(1).Sort
                    .header = xlYes
                    .MatchCase = False
                    .Orientation = xlTopToBottom
                    .SortMethod = xlPinYin
                    .Apply
                End With
            End With
        End If
    End If
End Sub

Initial Notes
The first thing that struck me about your code was that you literally have no variable declarations. Lines like :
cell_value = ...

Are pretty much the same as :
Dim cell_value as Variant
cell_value = ...

The only difference between the two is that the second is at least explicit about wanting a variant. The first is implicit.
First bit of advice avoid implicit commands as much as possible. The reason for this is quite simple, there is a tendency to think that the computer is magically doing something it shouldnt be, but really you told it to do exactly what it is doing and as a result, you have a bug that can be nearly invisible.
Consider for example :
myRange = Range("SomeRange")

This declares a myRange (which the reader expects to be a Range) and converts the range to an array. This in itself is confusing, but, even worse, I can still do :
Set myRange = Range("SomeRange")

And it is now a range reference (the only difference being the Set keyword). While it is easy to read the code and determine what is happening for us, you will inevitably lose a bug in there that you will have to search for.
Option Explicit to the Rescue!
Option Explicit is one of the best things in VBA. It is truly simple, but it makes the simplest of bugs super simple to prevent (and even simpler to find). With Option Explicit at the top of a module, the compiler will throw an error when a variable isnt declared.
' This won't compile. Note the minor (but potentially difficult to find) spelling error between Very and Vary.
Dim SomeVeryLongVariableName as Long
SomeVaryLongVariableName = 10

To make Option Explicit a breeze to use:

Open the Developer Window
Press CTRL+T and then CTRL+O.
Check the box for Require Variable Declaration.
While you're in there, I recommend going to the general tab and selecting Break in Class Module under error trapping.

Qualifying References
One of the most common mistakes someone new to VBA will make is doing:
SomeVariable = Range("SomeRange")

' or

SomeVariable = Range("SomeRange").Value

There are two problems with the first version. The problem that is solved by the second version is that we specify the property we are accessing. The default property of a Range is .Value so we don't need .Value, but it is discouraged to implicitly access .Value.
The second issue is that we rely implicitly on ActiveSheet.Range("SomeRange"). This is a silent killer. I refuse to work with the Active Anything unless I absolutely must and even then, I prefer not to. It is always best to specifically call the object you are working with.
' This is literally better than not using a worksheet reference at all
Dim Foo as Worksheet
Set Foo = ActiveSheet

...many lines later...

DoSomething Foo

Why is this little change better? It is using the active sheet! While not ideal, it at least ensures that Foo points to the same worksheet unless we explicitly change the worksheet it is pointing to. It is stronger than the ActiveSheet reference.
Even better would be:
Dim Foo as Worksheet
Set Foo = ThisWorkbook.WorkSheets("SomeFoo")

The ThisWorkbook object is the workbook that is running the code, and by using a string argument as a call to the collection we can return the specific worksheet back.
Working on the Worksheet
Now lets get into the meat of the problem. Your code is slow because you are operating on the worksheet. Its that simple. A hundred calls to the Worksheet.Range will be slower than a hundred calls to Data(x, y). An array is faster, and is easier to use.
Even worse is when you not only access the cells by a range reference, but when you do :
EntireRow.Delete

Now you've really upset the worksheet. It has to update calculations, it has to resize stuff, fix formatting (if in a table), check number formatting, etc. It is a costly operation. If you're deleting a lot of rows...avoid it at all cost.
Enter the world of arrays. Not only are they fast but they are easy. Worksheet.Cells(1, 1) becomes Data(1, 1). Once you load in the data to the array (Data) you can manipulate, access, delete the values all you want. The worksheet doesn't care. It doesnt see what is happening to the same data it was previously responsible for.
Putting It Together
I am not going to go through the code line by line, particularly because I already provided in-line comments to help make the code a bit easier to read. This will be a broad explanation of what the code does.

First, it loads in all the data from a ListObject (excel Table)
into an array. That's the easy part.
Once we have the data, we need to know the indices of the headers.
This makes manipulating the data much easier. It also allows you to
move columns around all you want without breaking the code (just
ensure the names are still there).
Using a custom Type we can store all of the data in a defined
structure. A Type is similar to a Struct in other languages. In
essence, it is a variable that has properties, but that isnt an
object. Thus, it cannot be New'ed up.
Loop through all of the rows, and create new records for cells with
multiple addresses. Since the Type cannot be New'ed, it will
retain old values. This means we dont need to re-create the entire
record for each new row. We just need to change the new values,
then add it to the collection.
Once the collection is loaded with records, we can translate them
into a new array that is appropriately sized. No need to add/remove
rows. It is just the right size at creation.
The OutputArray method will take an array and a worksheet and it
will clear the cells on that worksheet, put the array onto the
worksheet, and then turn that output into a table. Point it where
you want the output to go, and it will do the rest.

I didn't test the code on my end (I didnt want to bother creating a test table), but I imagine it should run in a matter of seconds.
Note : Microsoft Scripting Runtime
To use the code as is, you will need to add a reference to the Microsoft Scripting Runtime Library. There are plenty of resources for adding references, but ask if you get lost.
RubberDuck. Use It. Love It. Prof-It
I tend to be shameless about my plugs for Rubberduck, largely because the head of the tool, Mat's Mug, is unabashed in his attempts to convert everyone on SO to using RD. That said, it is an amazing tool, especially for beginners, and it would make most of the above comments stupidly easy to implement. Honestly, it would.
Check it out here: http://rubberduckvba.com/.
Wrapping Up
Let me know how the code above works for you, and do your best to use it as an example for future projects. If you manage to implement even half of those suggestions you'll save yourself potentially months of costly learning experiences through failed projects. Best of luck!
EDIT: Use this code instead to fix the error from above. The error is caused by adding a custom-type to a collection (I have never used Types outside of a class before so I didn't think of the error in advance). This approach is slightly more advanced, but it shouldnt be too complex.
In a Class Module named 'Record'
Option Explicit

Private Type TRecord
    ToField As String
    FromField As String
    Subject As String
    ReceivedDate As Date
    InFolder As String
    Size As String
    WeekDay As String
    RecordDate As Date
    Month As String
    Year As String
    Time As String
    InOut As String
End Type

Private this As TRecord

Public Property Get ToField() As String
    ToField = this.ToField
End Property
Public Property Get FromField() As String
    FromField = this.FromField
End Property
Public Property Get Subject() As String
    Subject = this.Subject
End Property
Public Property Get ReceivedDate() As Date
    ReceivedDate = this.ReceivedDate
End Property
Public Property Get InFolder() As String
    InFolder = this.InFolder
End Property
Public Property Get Size() As String
    Size = this.Size
End Property
Public Property Get WeekDay() As String
    WeekDay = this.WeekDay
End Property
Public Property Get RecordDate() As Date
    RecordDate = this.RecordDate
End Property
Public Property Get Month() As String
    Month = this.Month
End Property
Public Property Get Year() As String
    Year = this.Year
End Property
Public Property Get Time() As String
    Time = this.Time
End Property
Public Property Get InOut() As String
    InOut = this.InOut
End Property

Public Property Let ToField(value As String)
    this.ToField = value
End Property
Public Property Let FromField(value As String)
    this.FromField = value
End Property
Public Property Let Subject(value As String)
    this.Subject = value
End Property
Public Property Let ReceivedDate(value As Date)
    this.ReceivedDate = value
End Property
Public Property Let InFolder(value As String)
    this.InFolder = value
End Property
Public Property Let Size(value As String)
    this.Size = value
End Property
Public Property Let WeekDay(value As String)
    this.WeekDay = value
End Property
Public Property Let RecordDate(value As Date)
    this.RecordDate = value
End Property
Public Property Let Month(value As String)
    this.Month = value
End Property
Public Property Let Year(value As String)
    this.Year = value
End Property
Public Property Let Time(value As String)
    this.Time = value
End Property
Public Property Let InOut(value As String)
    this.InOut = value
End Property

This class uses a code pattern I learned from Mat's Mug. Declare the Type for the class as a Private Type, then declare a private this that refers to that type. As a result, you have an organized Type to hold your variables, and you get intellisense.
Once you do that, you just need to open up the property accessors. In this case, I made everything public. This isnt good practice, but I am avoiding teaching you too much at once (I would prefer not to use a class as is, but it is the best approach at this point).
This Code Goes in Your Module
Option Explicit

Sub New_Fix_Table()
    ' Be sure to add 'Option Explicit' at the top of your modules. This prevents undeclared variables from slipping through.

    ' Never use underscores in names. They have special meaning to the interpreter.
    ' table_size = Range("Table1").Rows.Count

    ' ## Not Needed due to UBound/LBound ##
    ' Dim tableSize As Long
    ' Be sure to also properly qualify you range references.
    ' TableSize = ActiveWorkbook.Range("Table1").Rows.Count - Without proper qualification, your Range is really ActiveWorkbook.Range
    ' tableSize = ThisWorkbook.Range("Table1").Rows.Count
    ' ## ##

    'Goes through Table1 in "To" column and fixes the recipients

    ' For loops such as these, I prefer for loops
    ' Do While i <= table_size

    ' I strongly prefer arrays for this purpose. If it was my own project, I even would use classes, but one step at a time for now.

    ' Change this to point to the correct worksheet.
    Dim inputSheet As Worksheet
    Set inputSheet = ThisWorkbook.Worksheets("TargetSheet")

    ' If your data is in a table, then you can use this method instead of referring to the range.
    Dim tableData As Variant
    tableData = inputSheet.ListObjects(1).Range.value

    ' Now, here is a trick I use when processing table data in a much more efficient manner.
    ' This does require a reference to Microsoft Scripting Runtime
    Dim headerIndices As Scripting.Dictionary
    Set headerIndices = GetHeaderIndices(tableData)

    ' Now we have a dictionary where we can use a key and return the index position of that key

    ' This is where it gets a little bit tricky. If we encounter a row with multiple emails, we need to duplicate the records.
    ' Otherwise, we want to keep the records as is. For this task, collections to the rescue!

    ' Having declared a Record Type, I can now use the Type as a container for my data (without needing a class)
    Dim initialRecord As record

    ' The records collection will contain the created records
    Dim records As Collection
    Set records = New Collection

    Dim i As Long
    ' We loop through arrays using LBound and Ubound (lower bound, upper bound). The '1' denotes rows, whereas '2' would denote columns.
    ' I add 1 to the lower bound so I can skip the header row.
    For i = LBound(tableData, 1) + 1 To UBound(tableData, 1)
        Set initialRecord = New record
        ' Set all the properties of the record.
        initialRecord.FromField = tableData(i, headerIndices("From"))
        initialRecord.Subject = tableData(i, headerIndices("Subject"))
        initialRecord.ReceivedDate = tableData(i, headerIndices("Received_Date"))
        initialRecord.InFolder = tableData(i, headerIndices("In_Folder"))
        initialRecord.Size = tableData(i, headerIndices("Size"))
        initialRecord.WeekDay = tableData(i, headerIndices("Weekday"))
        initialRecord.RecordDate = tableData(i, headerIndices("Date"))
        initialRecord.Month = tableData(i, headerIndices("Month"))
        initialRecord.Year = tableData(i, headerIndices("Year"))
        initialRecord.Time = tableData(i, headerIndices("Time"))
        initialRecord.InOut = tableData(i, headerIndices("In/out"))

        ' Split the addresses. If there are multiple addresses we dont need to rewrite the record, we just need to adjust the To field.
        Dim splitAddresses As Variant
        If InStr(tableData(i, headerIndices("To")), ";") > 0 Then
            splitAddresses = Split(tableData(i, headerIndices("To")), ";")

            Dim j As Long
            For j = LBound(splitAddresses) To UBound(splitAddresses)
                If Len(splitAddresses(i)) > 1 Then
                    Dim splitRecord As record
                    Set splitRecord = New record
                    ' Because of how objects are passed around, you cant copy a class through assignment. You must duplicate the properties manually into a new class.
                    splitRecord.FromField = initialRecord.FromField
                    splitRecord.Subject = initialRecord.Subject
                    splitRecord.ReceivedDate = initialRecord.ReceivedDate
                    splitRecord.InFolder = initialRecord.InFolder
                    splitRecord.Size = initialRecord.Size
                    splitRecord.WeekDay = initialRecord.WeekDay
                    splitRecord.RecordDate = initialRecord.RecordDate
                    splitRecord.Month = initialRecord.Month
                    splitRecord.Year = initialRecord.Year
                    splitRecord.Time = initialRecord.Time
                    splitRecord.InOut = initialRecord.InOut

                    initialRecord.ToField = splitAddresses(i)
                    records.Add splitRecord
                End If
            Next
        Else
            initialRecord.ToField = tableData(i, headerIndices("To"))
            records.Add initialRecord
        End If
    Next

    ' Now we have a colleciton of all of the records we need. Now, we need to translate those back into an array.
    Dim outputData As Variant

    ' The row is 0 based so we can add headers, but the headerIndices dictionary is already 1-based, so we leave the columns 1 based.
    ' Admittedly, I would avoid a mis-match of bases for re-dimming an array, I am only doing it this way to prevent confusion.
    ReDim outputData(0 To records.Count, 1 To headerIndices.Count)

    ' An array with the same base-dimensions would be one of the two following:
    ' ReDim outputData(0 To records.Count, 0 To headerIndices.Count - 1)
    ' ReDim outputData(1 To records.Count + 1, 1 To headerIndices.Count)
    ' You would then need to adjust the actual filling of the array as well.

    i = LBound(outputData, 2)

    Dim header As Variant
    ' Loop through all of the stored headers
    For Each header In headerIndices.Keys
        ' The LBound here dynamically points to the header row.
        outputData(LBound(outputData, 1), i) = header
    Next

    ' This way we can dynamically fill in the array.
    Set headerIndices = GetHeaderIndices(outputData)

    i = LBound(outputData, 2) + 1

    Dim outputRecord As record
    For Each initialRecord In records
        outputData(i, headerIndices("To")) = outputRecord.ToField
        outputData(i, headerIndices("From")) = outputRecord.FromField
        outputData(i, headerIndices("Subject")) = outputRecord.Subject
        outputData(i, headerIndices("Received_Date")) = outputRecord.ReceivedDate
        outputData(i, headerIndices("In_Folder")) = outputRecord.InFolder
        outputData(i, headerIndices("Size")) = outputRecord.Size
        outputData(i, headerIndices("Weekday")) = outputRecord.WeekDay
        outputData(i, headerIndices("Date")) = outputRecord.RecordDate
        outputData(i, headerIndices("Month")) = outputRecord.Month
        outputData(i, headerIndices("Year")) = outputRecord.Year
        outputData(i, headerIndices("Time")) = outputRecord.Time
        outputData(i, headerIndices("In/out")) = outputRecord.InOut
    Next

    ' Now we just have to put the output data somewhere. Let's reuse the sheet we pulled from.
    OutputArray outputData, inputSheet, "Output_Data"
End Sub

Public Function GetHeaderIndices(ByVal InputData As Variant) As Scripting.Dictionary
    If IsEmpty(InputData) Then Exit Function

    Dim headerIndices As Scripting.Dictionary
    Set headerIndices = New Scripting.Dictionary

    headerIndices.CompareMode = TextCompare

    Dim i As Long
    For i = LBound(InputData, 2) To UBound(InputData, 2)
        If Not headerIndices.Exists(Trim(InputData(LBound(InputData, 1), i))) Then _
           headerIndices.Add Trim(InputData(LBound(InputData, 1), i)), i
    Next

    Set GetHeaderIndices = headerIndices
End Function

Public Sub OutputArray(ByVal InputArray As Variant, ByVal InputWorksheet As Worksheet, ByVal TableName As String)
    Dim AddLengthH As Long
    Dim AddLengthW As Long

    If NumberOfArrayDimensions(InputArray) = 2 Then
        If LBound(InputArray, 1) = 0 Then AddLengthH = 1
        If LBound(InputArray, 2) = 0 Then AddLengthW = 1

        Dim r As Range
        If Not InputWorksheet Is Nothing Then
            With InputWorksheet
                .Cells.Clear
                Set r = .Range("A1").Resize(UBound(InputArray, 1) + AddLengthH, UBound(InputArray, 2) + AddLengthW)
                r.value = InputArray
                .ListObjects.Add(xlSrcRange, r, , xlYes).Name = TableName

                With .ListObjects(1).Sort
                    .header = xlYes
                    .MatchCase = False
                    .Orientation = xlTopToBottom
                    .SortMethod = xlPinYin
                    .Apply
                End With
            End With
        End If
    End If
End Sub

The only main difference is that now we are using an object instead of a type, and we must manually copy the object any time we want to create a new one (whereas, with the Type, we just changed the To field).


FizzBuzz implementation using the ternary operator This is my first time writing JAVA, and I'm trying to start off on the right track.

Using my C++ knowledge, I was able to understand the syntax for the ternary operator, but I'm not sure how it should be approached properly in JAVA.  I have used Ideone to test this, which include importss that apparently aren't even needed for this program, or so it seems.

I'd like a review over anything there is to offer, even if it involves telling me that starting with Ideone is not the best choice for whatever reasons.

import java.util.*;
import java.lang.*;
import java.io.*;

class BeginnerFizzBuzz {
    public static void main(String[] args) {
        for (int i = 1; i <= 100; ++i) {
            System.out.println(
                (i % 15 == 0) ? "FizzBuzz" :
                (i % 3 == 0) ? "Fizz" :
                (i % 5 == 0) ? "Buzz" :
                i
            );
        }
    }
}

even if it involves telling me that starting with Ideone is not the best choice for whatever reasons.

As a beginner, starting with Ideone is not the best choice IMO. For a number of reasons:

It is not a good practice to use import xxx.xxx.*. Only import the things that you actually need. In this case, you don't even need to import anything (because the things that you need are part of the java.lang package.
In IdeOne the filename is "Main.java" and there is no way to change that, which means that you will not learn that a public class in a file must have the same name as the file itself. I.e. the public class SomeClass must go in a file named SomeClass.java.
In IdeOne you are not able to declare a package name. A package name is mainly used to identify projects and the author of the code and so on. They are usually your domain-name backwards. For example, as I own zomis.net my package names are net.zomis.someproject. If you don't own a domain, well... make one up for now. com.jamal could work for you. Either way, usage of the "default"-package (i.e. not declaring a package at all) is discouraged.
In IdeOne there is no direct feedback for compiler errors. You have to click "Run" on your code to make sure that it has no compiler errors. In all modern Java IDEs you automatically get such feedback whenever you have finished writing a line of code (sometimes you have to hit Ctrl+S to save though before it will show the errors properly). This may not feel important at first, but once you get used to it you will really miss the feature in other IDEs.

As for the code itself, it isn't that bad. It is good that you removed IdeOne's throws Exception declaration.

Greg has already covered the aspects of the conditional operator, so there is only one thing I can possibly comment about, but this is just a personal opinion more than anything else and feel free to completely ignore this comment.

for (int i = 1; i <= 100; ++i) {

In Java, it is more common in such for-loops to use i++ rather than ++i. Although this has no effect whatsoever in this case, and I'm sure you're aware of the differences between i++ and ++i from your C++ (or is it ++C?) experience.

When using ++i or i++ alone (i.e. without an assignment to another variable), there is a myth that there is a performance difference in C++ and C, while apparently that is not the case.

In Java, it is also exactly the same (the same applies for C#, if you're wondering).

Of course, using i++ or ++i always matters when adding another assignment. If i = 1:

a = i++ will make a == 1
a = ++i will make a == 2
i == 2 after the statement in both cases


Create random list of size n using 2 enums in F# type Suit = Club = 1 | Diamond = 2 | Spade = 3 | Heart = 4
type Rank = Two = 2 | Three = 3 | Four = 4 | Five = 5 | Six = 6 | Seven = 7 | Eight = 8 | Nine = 9 | Ten = 10 | Jack = 11 | Queen = 12 | King = 13 | Ace = 14
type Card = { Suit:Suit; Rank:Rank }

let RandomHand (size:int) =
    let rndSuitIndex (rng:System.Random) = rng.Next(1, System.Enum.GetValues(typeof<Suit>).Length + 1)
    let rndRankIndex (rng:System.Random) = rng.Next(1, System.Enum.GetValues(typeof<Rank>).Length + 2)
    let randomCard (rng:System.Random) = {Suit=enum<Suit>((rndSuitIndex rng));Rank=enum<Rank>((rndRankIndex rng))}
    let cards (rng:System.Random) = List.init<Card> size (fun index -> randomCard rng)
    cards (System.Random())

As a C# programmer I'm trying to get into F#. I'm trying to create a function that returns a random list of cards. This currently works, but I'm sure this can be written MUCH shorter and cleaner.

Especially using the (rng:System.Random) 4 times feels like a stupid thing to do. Any tips?

I second Mark Seemann's remark regarding enums. It makes much more sense to use discriminated unions to describe the entities in your domain.

A randomizing function will never look completely nice and functional, as it uses a side-effect by definition. Nevertheless, I think there isn't much point in passing around the random seed. It can be initialized once in the beginning of your function.

I think things get much clearer when the function randomHand has the call to List.init as its last line, showing that it creates and returns a list. The card generating function could in principle be made into a lambda, but I couldn't squeeze it into less than 7 lines and fslint doesn't like it...

Here's my suggestion:

type Suit = Club | Diamond | Spade | Heart
type Rank = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace
type Card =
  { Suit: Suit
    Rank: Rank }

let randomHand size =
  let randomSeed = System.Random ()
  let randomCard _ =
    { Suit = match randomSeed.Next(1, 5) with
             | 1 -> Club | 2 -> Diamond | 3 -> Spade | 4 -> Heart
             | _ -> failwith "random value out of bounds"
      Rank = match randomSeed.Next(2, 15) with
             | 2  -> Two   | 3  -> Three | 4  -> Four | 5  -> Five | 6  -> Six
             | 7  -> Seven | 8  -> Eight | 9  -> Nine | 10 -> Ten  | 11 -> Jack
             | 12 -> Queen | 13 -> King  | 14 -> Ace
             | _ -> failwith "random value out of bounds" }
  List.init size randomCard

Since System.Random.Next() is not bound to a range by its type (int), I had to handle the potential case that it might return a value out of bounds.


Noughts and Crosses winner declaration in a game of variable square board size I have made a tic tac toe for two players and written down some functions to do the decision making about who is the winner. I have gone through some cases while testing but need advice to see if I am in the right track and also if all the winning positions are being taken care of.
I would like to know even if this can be simplified.

Here:
$state = ["&#10008;","-","-","-","-","&#10008;","-","-","-","-","&#10008;","-","-","-","-","&#10008;"]

The function is for grids starting from 3X3 to 7X7.

PHP

function whoIsWinning($state)
{
    $n = sqrt(count($state));
    $rows = $this->isWin($state, $this->genPaths($n, 0,     1,      $n, $n));
    $cols = $this->isWin($state, $this->genPaths($n, 0,     $n,     1,  $n));
    $diUp = $this->isWin($state, $this->genPaths(1, $n-1,  $n-1,   0,  $n));
    $diDn = $this->isWin($state, $this->genPaths(1,  0,     $n+1,   0,  $n));

    if ($rows !== '-') return $rows;
    if ($cols !== '-') return $cols;
    if ($diUp !== '-') return $diUp;
    return $diDn;
}

/**
 * Function to generate the paths to win
 * @param $count
 * @param $start
 * @param $incrementA
 * @param $incrementB
 * @param $lengthToWin
 * @return array
 */
function genPaths($count, $start, $incrementA, $incrementB, $lengthToWin)
{
    $paths = [];
    if($lengthToWin > 3) {
        $lengthToWin = $lengthToWin - 1;
    }
    for ($i = 0; $i < $count; $i++) {
        $path = [];
        for($j = 0; $j < $lengthToWin; $j++) {
            array_push($path, $start + $i * $incrementB + $j * $incrementA);
        }
        array_push($paths, $path);
    }
    return $paths;
}

/**
 * @param $state
 * @param $paths
 * @return string
 */
function isWin($state, $paths)
{
    for ($i = 0; $i < count($paths); $i++) {
        $currentPathResult = $this->isPathWin($state, $paths[$i]);
        if ($currentPathResult != '-')
            return $currentPathResult;
    }
    return '-';
}

/**
 * @param $state
 * @param $path
 * @return string
 */
function isPathWin($state, $path)
{
    $first = $state[$path[0]];
    for ($j = 1; $j < count($path); $j++) {
        $compareToFirst = $state[$path[$j]];
        if ($compareToFirst != $first)
            return '-';
    }
    return $first;
}

About the logic of assessing victory:

After each player's turn there can only be one winner, so no matter how you want to write the functional parts it would be best practice to write a return as soon as a victor is found so that you don't do any surplus processing.

The sample $state data:

You have provided a 4x4 grid, with only one player's marks on it -- which is not realistic.
You use - to identify unmarked cells -- I think blanks would be simpler/clearer.
Player X has a diagonal sequence of 4 marks, even though victory (by your rules) is attained by 3 consecutive marks on a 4x4 grid.

Some missing diagonal checks:

$diUp and $diDn have $count values of 1.  This is accurate on 3x3 grids only.

Because $lengthToWin is sqrt(count($state))-1, all grids larger than 3x3 will have 4 winning diagonal sequences in each orientation (running down-to-the-right & down-to-the-left).

Considering a 4x4 grid, the winning sequences from upper-left to lower-right are:

[ 0 , 5 , 10 ]
[ 1 , 6 , 11 ]
[ 4 , 9 , 14 ]
[ 5 , 10 , 15]

The first and last sequences share the internal cells with indexes of 5 & 10.

Here is a visual:

The same logic is applied to the sequences that start from the upper-right corner.

To crystallize... a 3x3 grid will have a total of 2 diagonal sequences, all other grids will have a total of 8 diagonal sequences.  The diagonal sequences obey a simple pattern, so you will have no trouble in generating the correct path for your function.

My tinkerings:

I experimented a little with what I understood of your concepts and tried to employ array functions rather than for loops (though they are sometimes slower, I think they are better descriptors of action).  It is not a very tidy snippet (consider it a "napkin" draft), I didn't bother refining it because I am not 100% sure of your usage nor what is the best way to display the result.

function hasWon(array $vals,$mark){
    return empty(array_diff($vals,[$mark])); // retain opponent's mark and blanks, if empty = victory / true
}

function findFirstWinningSequence(array $state,$width,$mark){
    $lengthToWin=($width>3?$width-1:$width);
    // process horizontal and vertical sequences:
    $chunks=array_chunk($state,$width);
    foreach($chunks as $i=>$chunk){
        // full-length/width checks:
        if(hasWon(array_slice($chunk,0,$lengthToWin),$mark)){ // scan rows from left
            return "$mark wins via row ".++$i." from left";
        }
        $column=array_column($chunks,$i);  // cache column elements
        if(hasWon(array_slice($column,0,$lengthToWin),$mark)){ // scan cols from top
            return "$mark wins via column ".++$i." from top";
        }
        // length/width-1 checks
        if($width>3 && hasWon(array_slice($chunk,-$lengthToWin),$mark)){ // scan rows from right, if needed
            return "$mark wins via row ".++$i." from right";
        }
        if($width>3 && hasWon(array_slice($column,-$lengthToWin),$mark)){ // scan cols from bottom, if needed
            return "$mark wins via column ".++$i." from bottom";
        }
    }
    // process UpperLeft-to-LowerRight diagonal sequences:
    $starts=[0];  // index of first element in set
    if($width>3){
        $starts+=[1,$width,$width+1];
    }
    $increment=$width+1;  // the increment between each cell in sequence
    foreach($starts as $start){
        $keys=array_fill_keys(range($start,$start+$increment*($lengthToWin-1),$increment),null);
        // if $start=0 & $width=4, $keys=array_fill_keys(range(0,0+5*(3-1)=10,5),null); producing: [0=>null,5=>null,10=>null]
        if(hasWon(array_intersect_key($state,$keys),$mark)){
            return "$mark wins via diagonal from ".++$start." running down and to the right";
        }
    }
    // process UpperRight-to-LowerLeft diagonal sequences:
    $starts=[$width-1];  // index of first element in set
    if($width>3){
        $starts+=[$width-2,2*($width-1),2*($width-1)+1];
    }
    $increment=$width-1;  // the increment between each cell in sequence
    foreach($starts as $start){
        $keys=array_fill_keys(range($start,$start+$increment*($lengthToWin-1),$increment),null);
        // if $start=3 & $width=5, $keys=array_fill_keys(range(4,3+4*(3)=15,4),null); producing: [3=>null,7=>null,11=>null,15=>null]
        if(hasWon(array_intersect_key($state,$keys),$mark)){
            return "$mark wins via diagonal from ".++$start." running down and to the left";
        }
    }
}
$state=['X','','','','','X','','','','','X','','','','O','O'];
$width=sqrt(sizeof($state));
$mark='X';
echo findFirstWinningSequence($state,$width,$mark);

To conclude, your coding structure seems suitably segmented/clean.  It only requires the logical tunes ups that I mentioned before my snippet.


Repeatable HTTP requests in Python I have a simple python script that's repeating a HTTP response/request. I would like to know how I could have constructed this better, particularly if there's a way I could have incorporated the slice operator to cut down on my variable usage.

For context - the response contained a JSON string in between the <ExecuteResult> flags that I'm removing currently with split()

import requests
import json
from pprint import pprint

url = "<redacted>"
cookies = {<redacted>}
headers = {<redacted>}
data="<redacted>"

submissions = input("How many submissions to create:")

while submissions > 0:
    response = requests.post(url, headers=headers, cookies=cookies, data=data)
    xml_string = response.content
    json_file = xml_string.split('<ExecuteResult>')[1]
    json_file = (json_file.split('</ExecuteResult>')[0]).replace("\\", "")
    json_response = json.loads(json_file)
    print "Created Id: " + json_response['_entity']['Id']
    submissions -= 1

If you are making many requests, it is worth it to have a look at requests.Session. This re-uses the connection to the server for subsequent requests (and also the headers and cookies).

I would also start separating your different responsibilities. One might be global constants (like your header and cookies), one a function that actually does the submission, one that creates the session and does each submission and then some code under a if __name__ == '__main__': guard that executes the code.

import requests
import json

COOKIES = {<redacted>}
HEADERS = {<redacted>}

def post(session, url, data):
    """Use session to post data to url.
    Returns json object with execute result"""
    response = session.post(url, data=data)
    json_file = response.content.split('<ExecuteResult>')[1]
    json_file = (json_file.split('</ExecuteResult>')[0]).replace("\\", "")
    return json.loads(json_file)

def post_submisssions(url, data, n):
    """Create a session and post `n` submissions to `url` using `data`."""
    session = requests.Session()
    session.headers.update(HEADERS)
    session.cookies = COOKIES

    for _ in xrange(n):
        json_response = post(session, url, data)
        print "Created Id:", json_response['_entity']['Id']

if __name__ == "__main__":
    url = "<redacted>"
    data = "<redacted>"
    post_submisssions(url, data, input("How many submissions to create:"))

I also added some rudimentary docstrings.

You could also change your parsing by using BeautifulSoup:

from bs4 import BeautifulSoup

def post(session, url, data):
    """Use session to post data to url.
    Returns json object with execute result"""
    response = session.post(url, data=data)
    soup = BeautifulSoup(response.content, 'lxml')
    return json.loads(soup.find('ExecuteResult'.lower()).replace("\\", ""))


Simplifying an AngularJs directive that counts the number of characters entered in a textarea I am trying to implement an AngularJS directive that would count the number of characters entered into a textarea and display it to the user.

Note: it will actually become much more complex later on and will become a full-fledged component that will be similar to the js component used by Stack Overflow for user comments: users will be notified how many more characters they may or must enter with different font colors.

Here is how the markup would look for the initial version:

       <cmp>
         <enhanced-textarea ng-model="name"></enhanced-textarea>

{{name}}

         <notice></notice>
       <cmp>

My js code is as follows:

var myModule = angular.module('myModule', []);
myModule.directive('cmp', function(){
    return {
        restrict: 'E',
        controller: 'cmpCtrl',
        replace: true,
        transclude: true,
        scope: {
            name: '='
        },
        template: '

'
    };
})
.controller('cmpCtrl', function ($scope, $element, $attrs) {
   $scope.$parent.$watch('name', function(newVal){
       if(newVal){
            $scope.$parent.updatedSize = newVal.length;
            console.log(newVal.length);
       }
   }, true);
})
.directive('enhancedTextarea', function () {
    return {
        restrict: 'E',
        replace: true,
        transclude: true,
        template: '<textarea ng-transclude></textarea>'
    };
})
.directive('notice', function () {
    return {
        restrict: 'E',
        require: '^cmp',
        replace: true,
        scope: {
            updatedSize: '='
        },
        template: '
{{size}}
',
        link: function($scope, $element, $attrs, cmpCtrl){
            console.log(cmpCtrl);
            $scope.$parent.$watch('updatedSize', function(newVal){
               if(newVal){
                  $scope.size = newVal;
               }
           }, true);
        }
    };
});

function myController($scope) {
    $scope.name = 'test';
};

I find it overly complex and I am sure it can be simplified.

Can anyone please advise and help perhaps by providing alternatives together with explanations?

Here is the fiddle

Massive overkill indeed,

<span>{{name.length}}</span>

will do the trick.

On the whole, I am not sure why you would use Angular to write an editor if you are not an expert in Angular. It adds a layer of complexity and eats into performance.


isLessThan function for structure with 7 integers The objective

I was trying to create a function that would compare 7 different integers. It should be able to be used to:

Sort the two structures in a consistent manner
Be able to detect if two structures are equal with !isLessThan(a,b) && !isLessThan(b,a)

The code

At first, I thought of using a hash function to reduce all the values to one, but then it occurred to me that I was over-engineering this simple problem.

This is language agnostic, but I ended up doing it like this:

bool isLessThan(const MyStruct& lhs, const MyStruct& rhs) {
    return
        lhs.a +
        lhs.b * 2 +
        lhs.c * 3 +
        lhs.d * 4 +
        lhs.e * 5 +
        lhs.f * 6 +
        lhs.g * 7
            <
        rhs.a +
        rhs.b * 2 +
        rhs.c * 3 +
        rhs.d * 4 +
        rhs.e * 5 +
        rhs.f * 6 +
        rhs.g * 7;
}

Don't re-invent the wheel (unless of course you want practice at doing that):

Instead of naming a bunch of elements that are all the same type, use an array for your structure's elements like std::array, or use a std::tuple. Or if you really don't want to change your structure's content, use std::tie to craft a tuple of your structure's elements on demand.
If you used a regular array use std::lexicographical_compare on the iterable elements of the two structures. A std::array or std::tuple already has non-member function support for operators like <, <=, >=, etc. though.
Kick back and enjoy a brewski. ;)  (only if allowed of course and be sure to drink responsibly etc. etc.).


Enum class for weight units I have some enum classes for units, like Weight units (KG and LB). I am translating the code to Qt C++ from Java, and I'm wondering what the best way to do this is as enums cannot have constructors in C++ that same way they do in Java (as far as I know).

Here is the Java class:

public enum WeightUnit {
  LB(WEIGHT_UNIT_LB, 0.45359237), //"lb" 1lb = 0.45359237 kg.
  KG(WEIGHT_UNIT_KG, 1.0);        //"kg"

  private String displayName;
  private double scale;

  private WeightUnit(String displayNameKey, double scale) {
      this.displayName = getDataMessages().getString(displayNameKey);
      this.scale = scale;
  }

  public String getDisplayName() {
      return displayName;
  }

  public String toString() {
      return displayName;
  }

  public static WeightUnit valueByName(String unitName) {
      for (WeightUnit value : WeightUnit.values()) {
          if (value.getDisplayName().equals(unitName) ||
                  value.name().equals(unitName)) {
              return value;
          }
      }
      throw new IllegalArgumentException(unitName);
  }

  public static double convert(double value, WeightUnit from, WeightUnit to) {
      if (from == to) return value;
      return value * from.scale/to.scale;
  }
}

Here is my C++ translation. It is not as elegant or clean as the Java version.

class WeightUnit {
  public:
    enum Value
    {
        LB,
        KG
    };

    WeightUnit() = default;
    constexpr WeightUnit(Value weightUnit) : value(weightUnit) {}

    bool operator==(WeightUnit a) const { return value == a.value; }
    bool operator!=(WeightUnit a) const { return value != a.value; }

    static double convert(double value, WeightUnit fromUnit, WeightUnit toUnit){
        return value * val(fromUnit.value)/val(toUnit.value);
    }

    static WeightUnit fromStr(QString str){
        if (str.compare(toStr(Value::LB)) == 0)
            return WeightUnit::LB;
        else if (str.compare(toStr(Value::KG)) == 0)
            return WeightUnit::KG;
        else
            throw QException();
    }

    static QString toStr(WeightUnit unit){
        if (unit == WeightUnit::LB)
            return "lb";
        else if (unit == WeightUnit::KG)
            return "kg";
        else
            throw QException();
    }

private:
    Value value;

    static double val(Value value){
        switch(value){
        case KG:
            return 1.0;
        case LB:
            return 0.45359237; //1 lb = 0.45359237 kg
        }
        throw QException(); //if not found, throw exception
    }
};

Is there any better way to tie values to each enum value in C++? In Java it is easy, because you can specify a constructor that requires certain parameters so you can be sure each enum value has an appropriate String and double value. Is there a way to do this in Qt/C++?

Even if Java and C++ display some similarities, particularly in the syntax, they are widely different languages and translating one into the other isn't automatic. Java is chiefly object-oriented, while C++ is more of a multi-paradigm language; one could even argue that it's drifting away from the object-oriented model towards a more functional approach designed to take advantage of compile-time customization and calculations.

So, it's best to take a step back and think again about your objectives and the means you have to achieve them when you transition from one to the other.

What you seem to need is a mapping between a unit, a textual representation and a floating precision proportion. Java allows for float based enums, which are thus a good candidate -even if the textual representation needs to be addressed somewhere else- but C++ doesn't. On the other hand, in the most recent version of the C++ standard, you can create and manipulate arrays at compile-time:

constexpr std::pair<std::string_view, float> weight_units[] {
    { "kg", 1. },
    { "lb", 0.45359237 },
    { "oz", 0.028349523125 },
};

constexpr auto weight_unit_value(std::string_view unit) {
    return std::find_if(std::begin(weight_units), std::end(weight_units), [unit](auto uv) {
        return uv.first == unit;
    })->second;
}

This code sadly compiles only with the latest version of clang, because gcc hasn't implemented the constexpr version of the standard algorithms yet. But writing it by hand would take 5 minutes. Or you can simply remove the constexpr qualifier.

This code has several advantages over the original Java version, the most important being that everything is defined once in one place. If you want to create a new unit in the original code, you need to modify the enum and create a new object with a custom name; here, you just extend the array.

Now, the array is also very handy if you want to parse a weight from a string, or convert a weight to a string:

// ex: float weight = parse_weight("1204.3 lb");
auto parse_weight(std::string_view weight) {
    auto coeff =  std::find_if(std::begin(weight_units), std::end(weight_units), [weight](auto uv) {
        return weight.ends_with(uv.first);
    })->second;
    return std::stof(weight.data()) * coeff;
}

auto to_string(float value, std::string_view unit_name) {
    auto result = std::to_string(value / weight_unit_value(unit_name));
    auto out = std::back_inserter(result);
    *out++ = ' ';
    std::copy(unit_name.begin(), unit_name.end(), out);
    return result;
}

Error handling could be added very easily (auto found = std::find_if(...); if (found == std::end(units)) throw unknown_unit("blabla");

Here's some code to toy with: https://wandbox.org/permlink/zj0hckfk6jR0vrXT


Simple Temperature Converter 2 in C I finally got around to redoing my Temperature conversion program. I incorporated many elements of everyone's comments, and am uploading the finished program. Any new, or problems that I missed? Maybe a few very late here where I am working. Main focus of this redo was keeping my functions short and single purposed.

#include <stdio.h>

void inter_face();
void welcome();
void option_prompt();
void input_temp_prompt();
int get_option();
float get_input_temp();
void display_F_to_C(float);
void display_C_to_F(float);
void display_off();
void display_error();
float F_to_C(float);
float C_to_F(float);

enum { F_TO_C = 1, C_TO_F = 2, OFF = 3 } option_type;

int main()
{
    inter_face();
    getchar();
}

void inter_face()
{
    int option = -1;
    float input_temp = 0.0;
    welcome();
    while (option != OFF) {

        option_prompt();
        option = get_option();

        if (option == F_TO_C || option == C_TO_F) {
            input_temp_prompt();
            input_temp = get_input_temp();
        }
        switch (option) {
        case F_TO_C:
            display_F_to_C(F_to_C(input_temp));
            break;
        case C_TO_F:
            display_C_to_F(C_to_F(input_temp));
            break;
        case OFF:
            display_off();
            break;
        default:
            display_error();
        }
     }
 }

 void welcome()
{
    printf("Temperature conversion Calculator!!\nPlease select an option:");
    printf("\n1.) F to C\t2.) C to F\t3.) off\n\n");
}

void option_prompt()
{
    printf("Option: ");
}

void input_temp_prompt()
{
     printf("Temp: ");
}

float get_input_temp()
{
    float input_temp = 0;
    scanf_s("%f", &input_temp);
    return input_temp;
}

int get_option()
{
    int option;
    scanf_s("%d", &option);
    return option;
}

void display_F_to_C(float converted_temp)
{
     printf("Celsius: %f\n", converted_temp);
}

void display_C_to_F(float converted_temp)
{
    printf("Fahrenheit: %f\n", converted_temp);
}

void display_off()
{
    printf("OFF\n");
}

void display_error()
{
    printf("Incorrect input, try again\n");
}

float F_to_C(float input_temp)
{
      return (5.0 / 9.0) * (input_temp - 32);
}

float C_to_F(float input_temp)
{
    return (9.0 / 5.0) * (input_temp)+32;
}

Firstly, I don't quite understand why are you declaring so much functions that consist of a single line dedicated to printing a string. They are only used once and in one file, so there's no need to use a function or constant. I suggest you to get rid of them and replace calls to these functions with their bodies. Also, put break; inside default case (Here you can learn more about the reason why you should do this):

    switch (option) {
        case F_TO_C:
            printf("Celsius: %f\n", F_to_C(input_temp));
            break;
        case C_TO_F:
            printf("Fahrenheit: %f\n", C_to_F(input_temp));
            break;
        case OFF:
            printf("OFF\n");
            break;
        default:
            printf("Incorrect input, try again\n");
            break;
    }

Secondly, I recommend to use puts() instead of printf() when printing simple strings as it is obviously simpler and places a newline automatically (And you use it often throughout your code). Note that this doesn't involve cases when printing formatted strings.

    switch (option) {
        case F_TO_C:
            printf("Celsius: %f\n", F_to_C(input_temp));
            break;
        case C_TO_F:
            printf("Fahrenheit: %f\n", C_to_F(input_temp));
            break;
        case OFF:
            puts("OFF"); // No need for printf()!
            break;
        default:
            puts("Incorrect input, try again"); // No need for printf() as well!
            break;
    }

Thirdly, I'd suggest to move the body of inter_face() function to main() as it is not used anywhere else and basically creates a run loop, so I don't see any reasons why you should place it in a separate function. In addition to this, you probably want to define your functions before they're used, thus moving all functions above main(). It's not necessary as the compiler will find them anyway, yet I reckon the source code looks better that way (Just imagine reading a book from the end to the beginning).

float F_to_C(float input_temp)
{
      return (5.0 / 9.0) * (input_temp - 32);
}

float C_to_F(float input_temp)
{
    return (9.0 / 5.0) * (input_temp)+32;
}

float get_input_temp()
{
    float input_temp = 0;
    scanf_s("%f", &input_temp);
    return input_temp;
}

int get_option()
{
    int option;
    scanf_s("%d", &option);
    return option;
}

int main()
{
    int option = -1;
    float input_temp = 0.0;

    printf("Temperature conversion Calculator!!\nPlease select an option:");
    printf("\n1.) F to C\t2.) C to F\t3.) off\n\n");

    while (option != OFF) {

        printf("Option: ");
        option = get_option();

        if (option == F_TO_C || option == C_TO_F) {
            printf("Temp: ");
            input_temp = get_input_temp();
        }

        switch (option) {
            case F_TO_C:
                printf("Celsius: %f\n", F_to_C(input_temp));
                break;
            case C_TO_F:
                printf("Fahrenheit: %f\n", C_to_F(input_temp));
                break;
            case OFF:
                puts("OFF"); // No need for printf()!
                break;
            default:
                puts("Incorrect input, try again"); // No need for printf() as well!
                break;
        }
    }

    getchar();
}

Fourthly, you should put function prototypes, enumerations and other objects that carry data (Of course, prototypes do not carry data, yet they belong in header files) into a separate header file (For instance, main.h). That way your source file looks a lot cleaner, and if someone wants to use these functions elsewhere, he can easily find this header file with needed prototypes within.

Fifthly, I'd consider either merging or getting rid of get_option() and get_input_temp() functions as they perform the same task, just with different data types. I suggest to create a single function called get_input() that returns a float (Since float can be compared to int without requiring you worry about loosing precision) instead if you don't want to put them inside main() as we did with other redundant functions before. You may then compare these variables normally as usual arithmetic conversions from int to float will occur when comparing float to int (You can learn more about such conversions here, here and here).

#include "main.h" // Prototypes and enum are there!

float F_to_C(float input_temp)
{
      return (5.0 / 9.0) * (input_temp - 32);
}

float C_to_F(float input_temp)
{
    return (9.0 / 5.0) * (input_temp)+32;
}

float get_input(void)
{
    float input = 0;
    scanf_s("%f", &input);
    return input;
}

int main()
{
    int option = -1;
    float input_temp = 0.0;

    printf("Temperature conversion Calculator!!\nPlease select an option:");
    printf("\n1.) F to C\t2.) C to F\t3.) off\n\n");

    while (option != OFF) {

        printf("Option: ");
        option = get_input();

        if (option == F_TO_C || option == C_TO_F) {
            printf("Temp: ");
            input_temp = get_input();
        }

        switch (option) {
            case F_TO_C:
                printf("Celsius: %f\n", F_to_C(input_temp));
                break;
            case C_TO_F:
                printf("Fahrenheit: %f\n", C_to_F(input_temp));
                break;
            case OFF:
                puts("OFF"); // No need for printf()!
                break;
            default:
                puts("Incorrect input, try again"); // No need for printf() as well!
                break;
        }
    }

    getchar();
}

Also, be sure to check chux's answer. It contains even more useful tips and tricks to improve your code. Especially scanf_s() checks, option = -1 change and math simplification.


Toggle four relays on/off based on bitmap stored in uint8_t I am using a one-byte bitmap to control four relays. I am writing a function which will take the bitmap stored as uint8_t, look to see which bits are set/cleared, then turn on/off the relays appropriately. The input value to my function could be anything from 0 to 15.

This is in a controls application, so I'd like this to thing to work pretty fast (not insane optimization, since I still have to wait 10ms for my relays to latch).

Here's the function so far (I stripped out the actual relay switching to simplify):

void
relayToggle(uint8_t relayBitmap)
{
    if ( 0b00000001 & relayBitmap == 0b00000001 ) { relayOn(1); }
    else if ( 0b00000001 & relayBitmap == 0 ) { relayOff(1); }
    else if ( 0b00000010 & relayBitmap == 0b00000010 ) { relayOn(2); }
    else if ( 0b00000010 & relayBitmap == 0 ) { relayOff(2); }
    else if ( 0b00000100 & relayBitmap == 0b00000100 ) { relayOn(3); }
    else if ( 0b00000100 & relayBitmap == 0 ) { relayOff(3); }
    else if ( 0b00001000 & relayBitmap == 0b00001000 ) { relayOn(4); }
    else if ( 0b00001000 & relayBitmap == 0 ) { relayOff(4); }
}

Use a loop to eliminate all that copy-pasta and get rid of some superfluous tests, branches and hard-coded constants:

void relayToggle(uint8_t relayBitmap)
{
    for (int r = 1; r <= 4; ++r)
    {
         if (relayBitmap & 1)
             relayOn(r);
         else
             relayOff(r);
         relayBitmap >>= 1;
    }
}


Dynamically update attribute of a same name in different classes I have this piece of code which I know can be improved greatly, but I simply don't know how. I've been googling for a little while, but truth to be told, I'm not really sure what I should be even looking for.

As you can see the code is very straight forward. Different classes have attributes of a same name, but I can't figure out how to dynamicaly swap between classes.

Please help me make it more dynamic, make it cleaner!!! Any help is much appreciated.

public void setHorsePurchaseInvoiceStatus(TransactionLine entity)
{
    if (entity.HorsePurchase != null)
    {
        switch (entity.Section)
        {
            case ("PI1"):
                entity.HorsePurchase.StatusPI1 = getCurrentSectionStatus(entity) ?? entity.HorsePurchase.PI1;
                break;
            case ("PI2"):
                entity.HorsePurchase.StatusPI2 = getCurrentSectionStatus(entity) ?? entity.HorsePurchase.PI2;
                break;
            case ("PI3"):
                entity.HorsePurchase.StatusPI3 = getCurrentSectionStatus(entity) ?? entity.HorsePurchase.PI3;
                break;
            case ("PI4"):
                entity.HorsePurchase.StatusPI4 = getCurrentSectionStatus(entity) ?? entity.HorsePurchase.PI4;
                break;
            case ("SI1"):
                entity.HorsePurchase.StatusSI1 = getCurrentSectionStatus(entity) ?? entity.HorsePurchase.SI1;
                break;
            case ("SI2"):
                entity.HorsePurchase.StatusSI2 = getCurrentSectionStatus(entity) ?? entity.HorsePurchase.SI2;
                break;
        }
    }
    else if (entity.HorseSale != null)
    {
        switch (entity.Section)
        {
            case ("PI1"):
                entity.HorseSale.StatusPI1 = getCurrentSectionStatus(entity)?? entity.HorseSale.StatusPI1;
                break;
            case ("PI2"):
                entity.HorseSale.StatusPI2 = getCurrentSectionStatus(entity)?? entity.HorseSale.StatusPI2;
                break;
            case ("PI3"):
                entity.HorseSale.StatusPI3 = getCurrentSectionStatus(entity)?? entity.HorseSale.StatusPI3;
                break;
            case ("PI4"):
                entity.HorseSale.StatusPI4 = getCurrentSectionStatus(entity)?? entity.HorseSale.StatusPI4;
                break;
            case ("SI1"):
                entity.HorseSale.StatusSI1 = getCurrentSectionStatus(entity)?? entity.HorseSale.StatusSI1;
                break;
            case ("SI2"):
                entity.HorseSale.StatusSI2 = getCurrentSectionStatus(entity)?? entity.HorseSale.StatusSI2;
                break;
            case ("SI3"):
                entity.HorseSale.StatusSI3 = getCurrentSectionStatus(entity)?? entity.HorseSale.StatusSI3;
                break;
        }
    }
    else if (entity.HorseDivideProfit != null)
    {
        switch (entity.Section)
            {
                case ("PI1"):
                    entity.HorseDivideProfit.StatusPI1 = getCurrentSectionStatus(entity) ?? entity.HorseDivideProfit.StatusPI1;
                    break;
                case ("SI1"):
                    entity.HorseDivideProfit.StatusSI1 = getCurrentSectionStatus(entity) ?? entity.HorseDivideProfit.StatusSI1;
                    break;
            }
    }
}

For one thing, getCurrentSectionStatus(entity) is duplicated multiple times. It would be better to put that in a local variable and use that variable instead.
That way if at some point you change the way you get the current section status,
you can make the change in one place.

However,
there are clearly deeper problems with this code.
Most noticeably,
field names such as StatusPI1, StatusPI2, ..., and StatusSI1, StatusSI2, ..., stink, as variable names containing numbers usually do.

Translated to pseudocode, the method looks like this:

if the TransactionLine contains a HorsePurchase: update a field in it depending on the section field of the line
or else, if the TransactionLine contains a HorseSale: update a field in it depending on the section field of the line
or else, if the TransactionLine contains a HorseDivideProfit: update a field in it depending on the section field of the line

At the minimum, it would be better to have separate TransactionLine subclasses to handle each type, for example HorsePurchaseTransaction, HorseSaleTransaction, HorseDivideProfitTransaction.
Then you could have an HorsePurchase.update method that takes a HorsePurchaseTransaction as parameter and apply the necessary changes,
and do similarly for the other types too.

This is still not enough to treat the odd StatusPI1, StatusPI2, and other fields, but just based on the posted code, I don't think there is enough information to propose an alternative approach. After splitting the TransactionLine as I described above, you could post the revised version and some more of the rest of the code in a new question,
so that we can address these issues and suggest further improvements.


Sum of First N Primes Task: Print sum of first 1000 primes.

public class PrimeSummation {
    public static void main(String[] args) {
        System.out.println(sumFirstPrimes(1000));
    }
    // Calculates the total of the first n primes
    public static int sumFirstPrimes(int n) {
        /* Since 2 is the only even prime it is pre-included;
        affords convenience of skipping other evens.
        3 is as well to skip an otherwise necessary check in isPrime() */
        int result = 5, count = 2;

        for (int i = 5; count < n; i += 2) {
            if (isPrime(i)) { result += i; count++; }
        }
        return result;
    }
    /* Determines if a number is prime, commented out irrelevant checks
    remove comments for general use */
    private static boolean isPrime(int num) {
        // if (num <= 3) { return num > 1; }
        if (/*(num & 1) == 0 || */ num % 3 == 0) { return false; }

        int limit = (int)Math.sqrt(num);

        for (int i = 5; i <= limit; i += 6) {
            if (num % i == 0 || num % (i + 2) == 0) { return false; }
        }
        return true;
    }
}

I'm trying to adjust my programming style to a "people first" paradigm. While any and all feedback is welcome, that is the focus.

Is there any ambiguity? Are the variable and method names adequate? I thought I could be more specific but the names would get significantly longer, is there some standard regarding the length of names?
Are the comments sufficient? I structure a general purpose method, but comment out otherwise redundant checks; rendering its use distinct to the task. Given specificity it was also made private. Is this good practice?
On the execution itself, is it satisfactory or are there some pitfalls I don't account for/optimizations I could make?

If you want a combination of readability and performance, consider the following solution.

public class Primes {
    private final boolean[] isComposite;
    private int n = 2;

    public Primes(int sieveSize) {
        this.isComposite = new boolean[sieveSize];
    }

    public static int overestimateOfNthPrime(int n) {
        // http://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number
        return (int)(1.5 * n * Math.log(n));
    }

    public int next() {
        try {
            return n;
        } finally {
            // Sieve of Eratosthenes: mark multiples of n as composite
            for (int i = 2 * n; 0 <= i && i < this.isComposite.length; i += n) {
                this.isComposite[i] = true;
            }
            do {
               n++;     // TODO: check array bounds
            } while (this.isComposite[n]);
        }
    }

    public static long sumFirstPrimes(int n) {
        Primes primes = new Primes(overestimateOfNthPrime(n));
        long sum = 0;
        while (n-- > 0) {
            sum += primes.next();
        }
        return sum;
    }

    public static void main(String[] args) {
        long start = System.nanoTime();
        System.out.println(sumFirstPrimes(Integer.parseInt(args[0])));
        System.err.println(System.nanoTime() - start);
    }
}

If your concern is "people first", then I think this is an improvement.  The sumFirstPrimes() function is more readable because the code that discovers more primes is decoupled from the code that sums them.  There are no magic numbers like 5 and 6, and no weird special cases.  Note that the readability comes mainly from the code structure, not from the comments on the code.

If your concern is performance, then the Sieve of Eratosthenes is a better algorithm for discovering many prime numbers.  It doesn't matter how many ugly hacks you use to optimize your trial division method — the Sieve simply scales better (up to a point).

$$\begin{array}{r|r|r}
\textrm{First } n \textrm{ primes} & \textrm{Legato's trial division} & \textrm{200_success's sieve} \\
\hline
10^3 &         ~1000\ \mathrm{\mu s} & ~2000\ \mathrm{\mu s} \\
10^4 &           ~10\ \mathrm{ms}    &   ~10\ \mathrm{ms}    \\
10^5 &          ~125\ \mathrm{ms}    &   ~40\ \mathrm{ms}    \\
10^6 &         ~4000\ \mathrm{ms}    &  ~500\ \mathrm{ms}    \\
10^7 & \color{gray}{\textit{DNF}}    &    ~7\ \mathrm{s}     \\
\end{array}$$

In the interest of full disclosure…

Making the estimate of the nth prime takes some mathematical knowledge.
I trust the estimate, so I didn't bother to check the array bounds.
For truly large problems (e.g 108), memory management for the Sieve would be a chore.


Character instance slowdown I'm making a Mario clone in PyGame and I am writing a function that, after releasing the left and right button while Mario is moving horizontally, slows him down until he is at rest. As of right now, the code I am using is functional and works the way it should. Though, I am not sure if there is a way I can write the following code more efficiently:

self.deacc = 0.5 # Always a positive number, never changed anywhere in the code.

if self.horzDir == 'l': # if mario is moving left.
    self.x += self.dx
    self.dx += self.deacc

    # To ensure marios velocity doesnt go below zero.
    if self.dx > (self.deacc * -1):
        self.dx = 0
else:
    self.x += self.dx
    self.dx -= self.deacc

    # Also to ensure marios velocity doesnt go below zero.
    if self.dx < self.deacc:
        self.dx = 0

Everything is working correctly, but I feel like it can be more efficient than this because the if and else statements are very similar, just with slightly different calculations. Any ideas?

The most important difference between your if and your else is this:

self.dx += self.deacc

vs.

self.dx -= self.deacc

The rest can work just fine without being in if or else.

Also, when you copy-paste code, which you apparently did to check the bounds on self.dx, you should change the comments. Both of your comments say "go below zero". It was a bit hard for me to understand the purpose of your if self.dx > (self.deacc * -1):.

If I understand your code correctly, and if my Python syntax skills are correct, I think it should work to do it like this:

self.x += self.dx
self.dx += (self.deacc if self.horzDir == 'l' else -self.deacc)

if Math.abs(self.dx) < self.deacc:
    self.dx = 0

If I understand your code correctly, you are stopping Mario whenever his velocity (self.dx) gets close enough to zero. This can be accomplished by taking the absolute value of self.dx (which will get rid of a possible negative sign) and check if it is below self.deacc. If it is, Mario should stop. I think describing this as "stop Mario if his speed is too slow" is more accurate than "ensure Mario's velocity doesn't go below zero."