Parse text file function This method takes a text file of my work schedule and parses it.  It works, but is kind of kludgey, and I'm looking for feedback and suggestions.  My first attempt at a file parser, and my first look at Python (I have dabbled in Java/Android and JavaScript).  I'm hoping that between the pseudocode and the comments it will be clear what is going on.

Pseudocode:

def read_body():
    f = open('file')
    tempList = []
    d = custom data object()
    for line in f:
        if line not empty line:
            if begins with a macron:    #denotes new day in the file
                prepare new/empty data object
                for line in f:
                    split line for whitespace
                    if line not empty line
                        if line is work
                            log it in data object
                        else its another activity
                            if pay value, also log it
            elif begins with an equal sign: #denotes end of day
    else:
        clean up
    f.close()

Full Code (it works):

macron = '¯'
equalSign = '='
underscore = '_'

def read_body(path, month_year):
    '''Reads schedule detail text file and generates pairing data objects for each work day.
        path:   file to open 'monthYEAR.txt'
        date:   MonthYEAREMPNO (month, year, employee number)
                from file header
                '''
    f = open(path)
    tempList = []
    d = WorkDay()
    for line in f:
        tempList = line.rsplit()
        if len(tempList) > 0:
            if macron in tempList[0]:       #begin work day
                #prepare new data object
                d.clear()
                d.month_year(month_year)
                for line in f:
                    tempList = line.rsplit()
                    if len(tempList) > 0:
                        if isWorkingDay(tempList[0]):   #parse tempList[1] date block MM/dd/YYYY
                            d.activity_name(tempList[0])
                            d.date_of_month(tempList[1])
                            line = f.next()
                            tempList = line.rsplit()
                            d.hours_worked(tempList[1])
                            d.pay(tempList[3])
                            break
                        else:       #is other activity (sick, off, vacation, etc), log date/time/pay
                            d.activity_name(tempList[0])   #tempList[0] failed isWorkingDay(), so just print.  Human readable string
                            for line in f:
                                if underscore in line:
                                    break
                                elif 'Credit:' in line:
                                    d.pay(line[8:12])
                            break
            elif equalSign in tempList[0]:   #end work day
                #drop activity object in "write to db" queue
                add_to_db(d)
    else:
        '''end of file, clean up partial data objects.  necessary because schedule text file ends with a macron'''
        #discard d if empty, raise error if non-complete, write to db if complete
        pass
    f.close()

As a recommendation for readability i suggest you replace

if len(tempList) > 0:

with

if tempList:

as the Empty List resolves to False.

It's also recommended to use the "with statement" when dealing with files to avoid errors.

with open('file') as f:
   ...

This will free any locks on the filesystem once this block is exited.


Forcing user to enter an integer I am new to C++ and would like to know the most efficient way of forcing a user to enter an integer. Here is my function that I have created. Please show me the best way and explain why it's better than this.

int getInt(){
    int x;
    while (true){
        cout << "Enter an int." << endl;
        cin.clear();
        while(cin.get() != '\n');
        cin >> x;
        if (!cin.fail()){
            return x;
        }
    }
}

I don't like while loops without a body. They are hard to read.

while(cin.get() != '\n');

// Even if the body is just a comment.
while(cin.get() != '\n')
{  /* Empty Body */ }

But what you are doing is basically ignoring the current line. It would be easier to do this with ignore()

std::cin.ignore(numeric_limits<streamsize>::max(), '\n');

But now that we have looked at it I don't really think you want to ignore the current line of input. Getting input screwed up (especially when working with interactive user input) is that you are mixing std::getline and operator>>. User input is line based so always read a line of input from the user then parse the input. Then you will not get screwed up by unread end of line markers.

Looping while(true) is dangerous when working with streams. Things have a tendency of becoming infinite. If your stream becomes bad (ie bad bit is set), then you will go into infinite loop. Clearing the bad bit and retrying is unlikely to make it better.

So I would re-write like this:

How about:

int getInt(std::istream& stream)
{
    // Only loop as long as the input is stream is usable.
    // Otherwise you enter an infinite loop.
    while (stream)
    {
        cout << "Enter an int." << endl;

        // Read a line of user input.
        std::string line;
        std::getline(stream, line);

        // Now convert user input to value.
        std::stringstream linestream(line);
        int               value;

        if (!(linestream >> value)) {
            continue;   // The input was not an integer.
        }               // So retry the loop.

        // You got a good value.
        // Do you care if there is stuff on the end of the line?
        // i.e.  If the user entered 56 f<enter> is that bad?
        //       If it is then you check to see if there is more valid input on the line.
        char  x;

        if (linestream >> x) {
            continue;    // There was good input (thus the input was bad).
        }
        return value;
    }
    // If you get here,
    // this means you ran out of input.
    // What do you do?
    // You could return a default value.
    // or throw an exception.
    return 0;

    // The trouble with either of these methods is that its hard to detect
    // the error situation. You need to explicitly check. That is why `operator>>`
    // works well. The stream goes bad when things get out of sync and the natural
    // operations cause the current operation to fail.
}

So an alternative to getInt() would be to extend operator>> for reading a line and getting an integer out of it.

 struct GetInt
 {
     int&  val;
     GetInt(int& v): val(v) {}

     friend std::istream& operator>>(std::istream& str, GetInt& data)
     {
         data.val  = getInt(str);
         return str;
     }
 };

Now you can use your line getting in a normal stream like operation.

 int val;
 if (std::cin >> GetInt(val))
 {
     // We correctly retrieved a value from the user.
 }


Improving AI for a Connect 3 game I am attempting to complete an assignment, which is basically Connect 3, instead of the classic Connect 4 game.  The AI I am using is the exact same as the opponent, but the opponent wins more because it goes first.  I've researched for days and cannot grasp MINIMAX, or think of ways to make this AI better.

public int getBestColumn(Player[][] state, Player player) {
    for (int c = 0; c < GRID_WIDTH; c++)

    int r = top(state, c);

    if (r >= 0) {
        Player[][] hypothetical = state;
        hypothetical[r][c] = player;
        if (getWinner(hypothetical, r, c) == player)
            return c;

        Player opponent = (player == Player.PLAYERX ? Player.PLAYERO : Player.PLAYERX);
        hypothetical[r][c] = opponent;
        if (getWinner(hypothetical, r, c) == opponent)
            return c;
        if(player==opponent)
            return c;

        hypothetical[r][c] = Player.NONE;

    }
}

    return (new Random()).getBestColumn(state, player);
}
}
}

I've researched for days and cannot grasp MINIMAX, or think of ways to make this AI better.

You can't really do MINIMAX without having an evaluation function. But even then, minimax is a bit complicated, but you could try something simpler:
Evaluation function
Make any function satisfying

f(state) = +A_LOT, if I win
f(state) = -A_LOT, if I lose
f(state) is bigger when the position looks better for me

Here, "looks better" simply means something like "me having 2 in a row is good", "me having 3 is even better". Just count things you believe are good.
Game tree search
You look at immediately wining turns, this is good. You also try to look at places where the other player can immediately win, this is also good. But you did it wrong (see below) and you don't do a real search.
A game tree search would mean, you do your hypothetical turn and then let the opponent try all moves (and so on). This can be as simple as two nested loops...
for all your turns {
  do your turn
  return if your won
  lost = false
  for all opponent's turn {
    do his turn
    lost = true if he won
    undo his turn
    break if lost
  }
  remember your turn as bad if lost
  undo your turn
}

Now you either returned with a winning move or remembered some bad moves or got no information at all. The further process should be obvious (winning move is clear, bad moves are to be avoided, that's all you know).
This can be generalized easily by using one more loop... you get one step smarter. And one more etc... however, a real depth search can go arbitrary deep, but try this for the start.
Combination
When going deeper, try using your evaluation function. This is still far from really smart, but it should be better than each idea alone.
Review
Player[][] hypothetical = state;

This looks like you'd have a state and an hypothetical state, which is not true, as it's the same array. So remove it to avoid confusion.
Player opponent = (player == Player.PLAYERX ? Player.PLAYERO : Player.PLAYERX);

Player should implement a method theOther() doing exactly this.
if (getWinner(hypothetical, r, c) == opponent)
        return c;

This alone is right, but it's in the same loop as finding your winning move. WRONG! If you can win at r=3 and the opponent can win at r=2, you'll play at r=2. You seem to be so scared of losing so that you give up a sure immediate win!
    if(player==opponent)
        return c;

WTF?
    }
}

    return (new Random()).getBestColumn(state, player);
}
}
}

WOW! So many closing braces and so nicely aligned...
The random move selection is fine if you don't know any better, but as I recently checked java.util.Random, it did not implement getBestColumn. This were a place for your evaluation function.


Recursive GCD using a lambda This works just fine, however, the assignment was to write a recursive "function".  I'm curious to see if this should count.

Any comments / suggestions/ stuff I should watch out for are appreciated.

#include <iostream>
#include <functional>
#include <cctype>
#include <cstdlib>

int main() {

    char go_again = 'Y';

    do {

        int lhs, rhs;
        std::cout << "Enter 2 integer values: ";
        std::cin >> lhs >> rhs;

        if (lhs < 0 || rhs < 0)
            std::cout << "Implicit converstion to positive integers.\n";

        std::function<int(int, int)>
            gcd = [&](int lhs, int rhs) -> int {
                return rhs == 0 ? std::abs(lhs) : gcd(rhs, lhs % rhs);
        };

        std::cout << "gcd == " << gcd(lhs, rhs) << '\n';
        std::cout << "Go again? <Y/N> ";
        std::cin >> go_again;

    } while (std::toupper(go_again) == 'Y');

}

Not that familiar with C++, but that certainly looks like recursion to me...

The variable gcd contains a function, which then calls itself.  The very definition of recursion.

But I would ask what you gain by not making it a regular function?


Excel column string to row number and vice versa Excel column letters to actual numbers, if you recall, Excel names its columns with letters from A to Z, and then the sequence goes AA, AB, AC... AZ, BA, BB, etc.
  You have to write a function that accepts a string as a parameter (like "AABCCE") and returns the actual column number. And then do the exact reverse, given column number return the column name.

Also verify complexity: \$O(\log n)\$, where \$n\$ is the input number while \$\log\$ is to base the base being considered (hexa, decimal or binary etc.).

public final class Excel {

    private Excel() {}

    public static int getExcelColumnNumber(String column) {
        int result = 0;
        for (int i = 0; i < column.length(); i++) {
            result *= 26;
            result += column.charAt(i) - 'A' + 1;
        }
        return result;
    }

    public static String getExcelColumnName(int number) {
        final StringBuilder sb = new StringBuilder();

        int num = number - 1;
        while (num >=  0) {
            int numChar = (num % 26)  + 65;
            sb.append((char)numChar);
            num = (num  / 26) - 1;
        }
        return sb.reverse().toString();
    }

    public static void main(String[] args) {
         Assert.assertEquals(53, getExcelColumnNumber("BA"));
         Assert.assertEquals("BA", getExcelColumnName(53));

         Assert.assertEquals(703, getExcelColumnNumber("AAA"));
         Assert.assertEquals("AAA", getExcelColumnName(703));

         Assert.assertEquals(26, getExcelColumnNumber("Z"));
         Assert.assertEquals("Z", getExcelColumnName(26));

         Assert.assertEquals(702, getExcelColumnNumber("ZZ"));
         Assert.assertEquals("ZZ", getExcelColumnName(702));

    }
}

Your code is basically fine, and your unit tests are good.  All I have is nitpicks.

"Excel" in the method names are a bit redundant.

In getExcelColumnNumber(), group - 'A' + 1 with parentheses as - ('A' - 1).  Then the compiler can generate 64 as a constant.

In getExcelColumnName(), the similarly named variables number, num, and numChar are confusing.

The complexity O(log n) is correct.  (With Big-O notation, the base of the logarithm is an unimportant detail, since the base just scales the logarithm by a constant factor, and constant factors are conventionally discarded with Big-O.  For example, O(log_26 n) = O(ln n / ln 26) = O(ln n).)

public final class ExcelColumn {

    private ExcelColumn() {}

    public static int toNumber(String name) {
        int number = 0;
        for (int i = 0; i < name.length(); i++) {
            number = number * 26 + (name.charAt(i) - ('A' - 1));
        }
        return number;
    }

    public static String toName(int number) {
        StringBuilder sb = new StringBuilder();
        while (number-- > 0) {
            sb.append((char)('A' + (number % 26)));
            number /= 26;
        }
        return sb.reverse().toString();
    }
}


Deep custom AngularJS Filter I need to filter projects using a searchbar, it should filter all properties of the projects with a few exceptions. It's working, but it's extremely slow, where can I make optimizations?
The "_" is from the library underscore.js

    <form>

            <input type="text" ng-model="searchText" class="form-control" placeholder="Suche..."/>

    </form>

       {{customer}}

Here's the filter:

.filter('searchProjects', ($rootScope, $filter) => {
    return (projects, query) => {
        if (projects) {
            var passFilter = projects.filter(p => {
                let backUpContacts = false;
                if (p) {

                    //If project has customer and customer has references, don't search in all of them
                    if (p.kunde && p.kunde.contacts) {
                        backUpContacts = p.kunde.contacts.concat([]);
                        //Only leave the selected Reference Contact in Customer's Contacts for Search
                        p.kunde.contacts = p.kunde.contacts.filter(contact => p.reference === contact.id);
                    }

                    //Search also for project leaders that have to be found first
                    let projectLeaders = [];
                    $rootScope.profiles.forEach(profile => {
                        profile.projects.forEach(role => {
                            if (role.project === p.id) {
                                let projectRole = role.masterData['Projektrolle'];
                                if (projectRole && ~projectRole.indexOf(864)) {
                                    projectLeaders.push(profile.firstName + " " + profile.lastName);
                                }
                            }
                        });
                    });
                    p["projectLeaders"] = projectLeaders;
                }
                let pContain = _.contains($filter('filter')(projects, query), p);
                delete p["projectLeaders"];
                if (backUpContacts) {
                    p.kunde.contacts = backUpContacts;
                }
                return pContain;
            });
            return passFilter;
        }
    };
})

I tried to improve it myself and it is much faster than before!
Here's my new code, feel free to comment on what can be further done to improve it.

    .filter('searchProjects', ($rootScope, $filter) => {
        return (projects, query) => {
            if (projects) {
                //Create project leader search object
                let projectLeaders = {};
                $rootScope.profiles.forEach(profile => {
                    profile.projects.forEach(role => {
                        let projectRole = role.masterData['Projektrolle'];
                        //864 = Projectleader Tag ID
                        if (projectRole && ~projectRole.indexOf(864)) {
                            let projectLeader = profile.firstName + " " + profile.lastName;
                            if (projectLeaders.hasOwnProperty(role.project)) {
                                projectLeaders[role.project].push(projectLeader);
                            } else {
                                projectLeaders[role.project] = [projectLeader];
                            }
                        }
                    });
                });

                return projects.filter(p => {
                    //delete customers' contacts to exclude from search
                    if (p.kunde && p.kunde.contacts) {
                        //Only leave the selected Reference Contact in Customer's Contacts for Search
                        p.kunde.contacts = p.kunde.contacts.filter(contact => p.reference === contact.id);
                    }
                    //if project has leaders, add them to it for searching
                    if (projectLeaders.hasOwnProperty(p.id)) {
                        p["projectLeaders"] = projectLeaders[p.id];
                    }
                    return Boolean($filter('filter')([p], query).length);
                });
            }
        };
    })


Sequential function call in JavaScript I've created this code which can call functions/ajax requests or pieces of code sequentially, using jQuery. The code not only can call functions/ajax requests or pieces of code sequentially but it also tracks when those calls fail or succeed and when the code fails it stops and doesn't exectue the rest of the queue.
(Bold italic are the names of the queues)
In my example i've 5 timeouts who get queued, the 2 first share a queue named first (1 and 1b) get executed at the same time and when those 2 finish and succeed(fire resolve) the next on the queue gets executed (next in queue is two which contains only 1 timeout). After two gets executed and succeed the third gets executed. I've coded in a way that the third fires a reject which changes the state of promise to reject(fails the request) and thanks to that the last timeout doesn't get called(to simulate a failed ajax request).

I know the code is pretty messy (it's my first version).  I would like some ideas on how I could structure this better or reduce the code considerably.

A problem I have with my code is that when I add a setTimeout, I have to include the deferred.resolve() in it.  I don't see a way around this.  Does anyone have an idea how to resolve this problem?

Code: http://jsfiddle.net/g55PC/

function myqueue(){
    var myself=this;
    var ord=[];// contains names used in promiseArr
    var funcArr=[];// contains setTimeout functions
    var me = $(document);

    this.add = function (func, name) {
        if (typeof funcArr[name] !== "object") funcArr[name] = [];

        funcArr[name].push(func);
        if($.inArray(name, ord)==-1){
            ord.unshift(name);
        }

    }

    this.call= function (name) {

        me.queue("deferQueue", function () {

            var promiseArr=[];

            for(func in funcArr[name]){
                promiseArr[func]=(function(){
                    var dfd = new jQuery.Deferred();
                    funcArr[name][func](dfd);
                    return dfd.promise();
                })();
            }

            $.when.apply($,promiseArr).then(function () {
                console.log("Success "+name);
                me.dequeue("deferQueue");
            }, function () {
                console.log("Fail "+name);
            });
        });
    }
    this.start = function () {
        while(ord.length>0) {
            this.call(ord.pop());
        }
        me.dequeue("deferQueue");
    }
};
myPlugin = new myqueue();
myPlugin.add(function (dfd) {
    setTimeout(function () {
        $("#result").append("
1
");
        //console.log("1");
        dfd.resolve();
    }, 2000);
}, "first");//first = queue Name
myPlugin.add(function (dfd) {
    setTimeout(function () {
        $("#result").append("
1b
");
        //console.log("1b");
        dfd.resolve();
    }, 1000);
}, "first");//first = queue Name
myPlugin.add(function (dfd) {
    setTimeout(function () {
        $("#result").append("
2
");
        //console.log("2");
        dfd.resolve();
    }, 1000);
}, "second");//second = queue Name
myPlugin.add(function (dfd) {
    setTimeout(function () {
        $("#result").append("
3
");
        //console.log("3");
        dfd.reject();
    }, 500);
}, "third");//third = queue Name
//forth will not be fired since third failed
myPlugin.add(function (dfd) {
    setTimeout(function () {
        $("#result").append("
4
");
        //console.log("4");
        dfd.resolve();
    }, 3000);
}, "forth");//forth = queue Name

myPlugin.start();

I like the idea of your code but you defenitely have some bugs and convention issues that should be dealt with:

Major bug: call does not remove funcArr[name] after iterating them so if you add something to the "first" queue and call the first queue, adding something to the first queue will still have the functions from before you called the queue earlier. I created a (demo of the issue); as you see the alert will be shown twice as funcArr[name] is never emptied
You're storing keys (function names) in the array funcArr. funcArr should be a hash object rather than an array.
You're using for..in on an array (why this is bad) and moreover, the variable func will be global. Use a regular for loop instead here. I'd recommend using $.each here. With $.each you'd write the loop

$.each(funcArr, function(i, fn) {
    var dfd = $.Deferred();
    fn(dfd);
    promiseArr.push(dfd.promise());
});

You're module pattern seems off... 1) its common convention that a class name should be capitalized, ie MyQueue, 2) theres no real reason to use the this keyword if you're not planning to add these functions on prototype, 3) In this.start your line this.call(ord.pop()); is a bit confusing.
As you were not making use of prototype in your function I adapted your code to use the "module pattern". This allows your module to be created without the new keyword whereas before it would of caused major issues.

Here's how I would write your queue. I added comments on most of my cahnges

function myqueue(){
    var ord=[];
    var funcHash = {}; // Use a hash as you're using keys rather than indicies
    var me = $(document);//(minor)convention would be to name this $doc

    var plugin = {
        add: function (func, name) {
            if(!funcHash.hasOwnProperty(name)) {//name does not exist yet
                funcHash[name] = [];
                ord.unshift(name);
            }
            funcHash[name].push(func);//now just queue the function
        },

        call: function (name) {
            me.queue("deferQueue", function () {
                var promiseArr=[];
                var funcArr = funcHash[name];

                //funcArr is a hash of arrays don't use for in
                //also func was a global variable!]

                $.each(funcArr, function(i, fn) {
                     var dfd = new jQuery.Deferred();
                     fn(dfd);
                     promiseArr.push(dfd.promise());
                });

                //I assume you want to remove the functions after you call them so requeing the same name doesn't add to the old queue
                delete funcHash[name];

                $.when.apply($,promiseArr).then(function () {
                    console.log("Success "+name);
                    me.dequeue("deferQueue");
                }, function () {
                    console.log("Fail "+name);
                });
            });
        },

        start: function () {
            while(ord.length>0) {
                plugin.call(ord.pop());
            }
            me.dequeue("deferQueue");
        }
    };

    return plugin;
};

http://jsfiddle.net/g55PC/2/

As for the second question of having to do the .resolve() in the timeout, you may want to consider adding a helper to your myqueue module along the lines of

//helper function for automatically managing a delay using timeout
addDelayed: function(fn, name, delay) {
    this.add(function(dfd) {
        setTimeout(function () {
            fn(dfd);
            dfd.resolve();
        }, delay || 250);
    }, name);
}

So your old pattern code be reduced to just:

myPlugin.addDelayed(function (dfd) {
    $("#result").append("
1
");
}, "first", 1000);


Pandas iteration over rows for features calculation I have a pandas data frame and I want to calculate some features based on some short_window, long_window and bins values. More specifically, for each different row, I want to calculate some features. In order to do so, I move one row forward the df_long = df.loc[row:long_window+row] such as in the first iteration the pandas data frame for row=0 would be df_long = df.loc[0:50+0] and some features would be calculated based on this data frame, for row=1 would be df_long = df.loc[1:50+1] and some other features would be calculated and continues.

from numpy.random import seed
from numpy.random import randint
import pandas as pd
from joblib import Parallel, delayed

bins = 12
short_window = 10
long_window = 50

# seed random number generator
seed(1)

price = pd.DataFrame({
    'DATE_TIME': pd.date_range('2012-01-01', '2012-02-01', freq='30min'),
    'value': randint(2, 20, 1489),
    'amount': randint(50, 200, 1489)
})

def vap(row, df, short_window, long_window, bins):

    df_long = df.loc[row:long_window+row]
    df_short = df_long.tail(short_window)

    binning = pd.cut(df_long['value'], bins, retbins=True)[1]
    group_months = pd.DataFrame(df_short['amount'].groupby(pd.cut(df_short['value'], binning)).sum())

    return group_months['amount'].tolist(),  df.loc[long_window + row + 1, 'DATE_TIME']

def feature_extraction(data, short_window, long_window, bins):

    # Vap feature extraction
    ls = [f"feature{row + 1}" for row in range(bins)]
    amount, date = zip(*Parallel(n_jobs=4)(delayed(vap)(i, data, short_window, long_window, bins)
                                                for i in range(0, data.shape[0] - long_window - 1)))
    temp = pd.DataFrame(date, columns=['DATE_TIME'])
    temp[ls] = pd.DataFrame(amount, index=temp.index)
    data = data.merge(temp, on='DATE_TIME', how='outer')

    return data

df = feature_extraction(price, short_window, long_window, bins)

I tried to run it in parallel in order to save time but due to the dimensions of my data, it takes a long of time to finish.

Is there any way to change this iterative process (df_long = df.loc[row:long_window+row]) in order to reduce the computational cost? I was wondering if there is any way to use pandas.rolling but I am not sure how to use it in this case.

Any help would be much appreciated!
Thank you

Just some stylistic suggestions

Constants

Constants in your program should be UPPERCASE. (PEP 8)

bins -> BINS
short_window -> SHORT_WINDOW
long_window -> LONG_WINDOW
price -> PRICE

Docstrings

You can add docstrings to your functions to allow more description about the function and
about the parameters it accepts and the value(s) it returns, if any. (PEP 8)

def vap(row, df, short_window, long_window, bins):
    """
    Description Here

    :param row: Description Here
    :param df: Description Here
    :param short_window: Description Here
    :param long_window: Description Here
    :param bins: Description Here

    :return: Description Here
    """

Type Hints

You can add type hints to your functions to show what types of parameters are accepted, and what
types are returned.

You can also use typing's NewVar to create custom types to return.

from typing import List

PandasTimeStamp = NewType("PandasTimeStamp", pd._libs.tslibs.timestamps.Timestamp)

def vap(row: int, df: pd.DataFrame, short_window: int, long_window: int, bins: int) -> List, PandasTimeStamp:
    ...


Dynamic homepage with PHP - making things too complicated? I am trying to show the 6 most popular products on my homepage from left to right, in two rows. My code actually works... but I have the feeling I am making things way too complicated. Is there a simpler way to do this?

Here is my code:

$dynamicList = "";
$sql = mysql_query("SELECT * FROM products ORDER BY popularity DESC LIMIT 6");
$productCount = mysql_num_rows($sql); //Count the output amount
if($productCount>0){
    $currentRow=0;
    $dynamicListLeft='
';
    $dynamicListMiddle='
';
    $dynamicListRight='
';
    while($row=mysql_fetch_array($sql)){
            $currentRow=$currentRow+1;
            $id = $row["id"];
            $product_name = $row["product_name"];
            $date_added=strftime("%b %d, %Y", strtotime($row["date_added"]));

            if($currentRow==1 || $currentRow==4) {
                $dynamicListLeft .='

';
            } else {
                    if($currentRow==2 || $currentRow==5) {
                        $dynamicListMiddle .='

';
                    } else {
                            if($currentRow==3 || $currentRow==6){
                                $dynamicListRight .='

';
                            }
                        }
                }

        }
        $dynamicListLeft .='
';
        $dynamicListMiddle .='
';
        $dynamicListRight .='
';
        $dynamicList .=$dynamicListLeft;
        $dynamicList .=$dynamicListMiddle;
        $dynamicList .=$dynamicListRight;

}

Later on in my body I echo the dynamiclist.

I hope somebody can show me the way to make this smoother?

Thanks!

Let's go for a step-by-step cleanup.

1) Get rid of repetition by using a variable to store your html code common to the different branches.

2) Remove useless levels of indentation to make things easier to follow.

The inside of the while loop is now :

        $currentRow=$currentRow+1;
        $id = $row["id"];
        $product_name = $row["product_name"];
        $date_added=strftime("%b %d, %Y", strtotime($row["date_added"]));
        $link = '

';
        if($currentRow==1 || $currentRow==4) {
            $dynamicListLeft .= $link;
        } else if($currentRow==2 || $currentRow==5) {
            $dynamicListMiddle .= $link;
        } else if($currentRow==3 || $currentRow==6){
            $dynamicListRight .= $link';
        }

(I could move the definition of link out of the loop but I guess in your real situation, the content depends on $row).

3) You can try to store your content in an array instead of using different variables. It removes a bit of logic and makes things easier to update if you want 2 or 4 columns in the future. It also removes some code duplication :

$cols=array('','','');
$nbCol=count($cols);
$currentRow=0;
while($row=mysql_fetch_array($sql)){
        $id = $row["id"];
        $product_name = $row["product_name"];
        $date_added=strftime("%b %d, %Y", strtotime($row["date_added"]));
        $link = '

';
        $cols[$currentRow%$nbCol] .= $link;
        $currentRow=$currentRow+1;
}
for ($col as $i => $content)
{
   $dynamicList .= '
' . $content . '
';
}

4) So far, the comments were about the php code and not the HTML output it produces. My last comment is more of a question but wouldn't there be a way to have your HTML defined in such a way that you don't need such a complicated logic. Basically, at the moment, the whole point is that your HTML code contains reference to your item in this order : 1,4,2,5,3,6. Things would be easier if you could have them in the natural order (1,2,3,4,5,6) in your HTML code and then update your HTML to display them in such a such a way.
My HTML skills are way too limited to answer this question...


A decoding "guessing game" So, I have decided to make a little "guessing game" where the user tries to decode what the encoded piece of text prompted. I'm sure it works. However, I know that there are places where I can improve. I am open to any constructive criticism about this. This program was done in HTML + JavaScript.

<!DOCTYPE HTML>

  <META CHARSET="UTF-8" />
  <TITLE>Decryption Guessing Game</TITLE>

Text:

  <form name="game" action="#" onsubmit="return validateForm()">
    Decrypt: <input type="text" name="text">
    <input type="submit" value="Check!">
  </form>

Use lowercase tag names and attributes

Quoting Quentin from "Is it bad to use uppercase letters for html tags?":

  The only relevant parts of specifications say:

  HTML tag and attribute names are case insensitive.
  XHTML tag and attribute names are case sensitive and must be lower case

  Stuff that isn't mentioned in any standard:

  Lower case is generally considered easier to read
  Lower case is most common (and what people are used to working with)
  Holding down the shift key or toggling CAPS LOCK all the time is a pain

Don't use onsubmit attribute

It's a rather bad code style to still use attributes like this one, these days. For example, that way the submit event would not be raised by form.submit() function, which you may want to use later. Use addEventListener() instead, it's supported even by IE9+.

Don't use deprecated language attribute of script tag

Not only it is deprecated and it's not used anymore, but also a standard regarding this attribute's values never existed. You should use type="text/javascript" instead or no attribute at all, since in HTML5 in case of lack of specification of language used by script tag, it is assumed to be JavaScript, anyway.

Randomness source and distribution

Your function randomInt() uses Math.random() to obtain random values in a manner that will give you non-uniform distribution of returned values. It should also be noted, that it provides non-cryptographically secure randomness, although this is not a problem in this case.

Comments

Not all comments are useful, especially this invalid one:

var encryptedText = []; // the decrypted pieces of text.

Global scope

You shouldn't declare variables in the global scope, like you did between the two functions you made. Break that code into another function or combine with already existing ones, if appropriate.

Use map()

This

var encryptedText = []; // the decrypted pieces of text.

for (var i = 0; i < text.length; i++) {
  encryptedText.push(window.btoa(text[i]));
}

could be shortened to one, very straight-forward line:

var encodedText = text.map(window.btoa);

Use .textContent instead of .innerHTML

Since you don't want nor need to have your string parsed, you should use .textContent property instead of .innerHTML.

Inconsistent quotation marks

You mix single ('') and double ("") quotation marks. Use single ones, except where it would force you to escape what's between them.

Dot notation

This

var form = document.forms['game']['text'];

would look better and be written by most as:

var form = document.forms.game.text;

Use strict equality operator

You should use strict equality operator in your code, as it doesn't performs type conversion and is generally considered a good practice.

Don't location.reload()

You don't need to location.reload(), just reset() the form.

Don't encode before necessary

Currently you are encoding all strings before they are even randomly chosen. There is no need to do that. What if there were thousands of strings? Reverse the order of operations, first choose random string and just then encode it. That way, you won't even need to store results of encoding, by the way.

Naming

What you do is encoding and decoding with Base64, but one variable is named encryptedText. Comment on the same line have exactly the same naming issue. There is no encryption involved in your code, at all.

Replace two location.reload()s with one

You could remove two instances of location.reload() that you have in your code and add just one below the chain of conditional checks.

Edit: Although remember that even this one location.reload() should be replaced with form resetting, as mentioned before.

Empty string submission check

Instead of checking if (input === '') you could add required="" attribute to your input tag.


Retrieve the shared words from files I have two files of dip.md and tp.md, which copied respectively from Think Python and Dive Into Python 3

By comparing them, I retrieved the shared words by the following procedures:

Read contents from files

def read(filename):
    with open(filename) as file:
        content = file.read()
    return content
dip = read('dip.md')
tp = read('tp.md')

In [49]: dip
Out[49]: '- -  \n\n    You are here:  •\n\n    # Dive Into Python 3\n\n    Dive Into Python 3 covers Python 3 and its differences from Python 2. Compared to [Dive Into Python](http://diveintopython.net/), it’s about 20% revised and 80% new material. The book is now complete, but [feedback is always welcome](http://www.diveintopython3.net/about.html).\n\n
...
In [50]: tp
Out[50]: 'Think Python: How to Think Like a Computer Scientist\n\nAllen B. Downey\n\n2nd Edition, Version 2.2.23\n\nPreface\nThe strange history of this book\nAcknowledgments\nContributor List\nThe way of the program\nWhat is a program?\nRunning Python\nThe first program\nArithmetic operators\nValues and types\nFormal and natural languages\nDebugging\nGlossary\nExercises\nVariables, expressions and statements\nAssignment statements\nVariable names\nExpressions and statements\nScript mode\nOrder of operations\nString operations\nComments\nDebugging\nGlossary\nExercises\nFunctions\nFunction calls

Clear data using string.punctuation

def clear_data(cont):
    for data in cont:
        if data in punctuation:
            cont = cont.replace(data, ' ')
    cont = cont.replace('\n', ' ')
    cont = cont.lower()
    return cont
dip_cont = clear_data(dip)
tp_cont = clear_data(tip)

Retrieve the qualified list

def get_qualified_list(cont):
    cont_list = cont.split(' ')
    qualified_list = [i for i in cont_list if i.isalpha()]
    return qualified_list
dip_list = get_qualified_list(dip_cont)
tp_list = get_qualified_list(tp_cont)

Get their intersection

In [51]:  print(set(dip_list) & set(tp_list))
{'is', 'study', 'Refactoring', 'with', 'and', 'the', 'first', 'Expressions', 'book', 'as', 'comprehensions', 'of', 'Strings', 'program', 'names', 'expressions', 'Case', 'to', 'Files', 'Classes', 'Objects', 'method', 'are', 'Python', 'The', 'in', 'new', 'strings'}

This solution is a bit too much for such a task which can be easily handled on 'MS Word'.

How can such a task be accomplished in an easy way?

This solution is a bit too much for such a task

Not even close. Welcome to the Natural Language Processing space :)

In order to properly compare the English texts we at least need to apply the following things:

make the comparison case-insensitive
remove punctuation and retain alphabetic words only
remove stop words
lemmatize words

We can make use of the awesome nltk Python library to help us tokenize, remove the stop words and lemmatize. Here is something more or less generic that works for HTML documents (you can modify the "download content" part if you are working with markdown or other document types):

from bs4 import BeautifulSoup
from nltk import word_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
import requests

ENGLISH_STOPS = set(stopwords.words('english'))

def download_content(url):
    response = requests.get(url)
    soup = BeautifulSoup(response.content, "html.parser")

    return soup.get_text()

def preprocess(text):
    tokens = word_tokenize(text)

    # lowering
    lower_tokens = [token.lower() for token in tokens]

    # Retain alphabetic words: alpha_only
    alpha_only = [t for t in lower_tokens if t.isalpha()]

    # Remove all stop words: no_stops
    no_stops = [t for t in alpha_only if t not in ENGLISH_STOPS]

    # Lemmatize all tokens into a new list: lemmatized
    wordnet_lemmatizer = WordNetLemmatizer()
    lemmatized = [wordnet_lemmatizer.lemmatize(t) for t in no_stops]

    return set(lemmatized)

def compare_documents(*urls):
    contents = [download_content(url) for url in urls]

    return set.intersection(*[set(preprocess(content)) for content in contents])

if __name__ == '__main__':
    print(compare_documents(*[
        "http://greenteapress.com/thinkpython2/html/index.html",
        "http://www.diveintopython3.net"
    ]))

Prints:

{'object', 'generator', 'string', 'first', 'study', 'book', 'name', 'refactoring', 'new', 'case', 'program', 'expression', 'file', 'python', 'method', 'class', 'common', 'comprehension'}

These are, of course, like in your example, not the full books that were compared - just the contents pages of the two.

By the way, here are the common words between your question and my answer (computed using the proposed code):

{
    'task', 'python', 'content', 'following', 'two', 'welcome',
    'natural', 'much', 'return', 'new', 'list', 'book', 'print', 'like',
    'compared', 'def', 'word', 'http', 'punctuation', 'solution', 'bit', 'set'
}


Goldbach's conjecture algorithm I did a Goldbach's Conjecture exercise and got it to work. It's pretty slow though and I was wondering how I could optimize it.

number = int(input("Enter your number >> "))
print("\nCalculating...")
if number % 2 == 0: #Only even numbers
    primes = primenums(number) #returns all prime numbers <= input number
    addend1 = primes[0]
    addend2 = primes[0]

    while addend1 + addend2 != number:
        if primes[-1] == addend2:
            addend2 = primes[primes.index(addend1) + 1]
            addend1 = primes[primes.index(addend1) + 1]
        else:
            addend2 = primes[primes.index(addend2) + 1]

Right now, up to 10,000 the algorithm is pretty fast, but at 100,000 it takes about 3 seconds to finish. Is that just how it is or could I make it faster?

One thing that makes your code slow is your repeated calls to primes.index. Each of these calls needs to linearly scan primes until it finds the value you are looking for, making this \$\mathcal{O}(n)\$. This is especially bad in the first if case since you do this twice with exactly the same argument. Instead just keep the index around in addition to the number:

def goldbach_keep_index(number):
    if number % 2 == 1: #Only even numbers
        raise ValueError("Goldbach conjecture is only defined for even numbers")
    primes = primenums(number) #returns all prime numbers <= input number
    i, j = 0, 0
    addend1 = primes[i]
    addend2 = primes[j]

    while addend1 + addend2 != number:
        if addend2 == primes[-1]:
            i = j = i + 1
            addend2 = primes[i]
            addend1 = primes[i]
        else:
            j += 1
            addend2 = primes[j]
    return addend1, addend2

Note that I made this a function, so you can reuse it.

Your main calling code could look like this:

if __name__ == "__main__":
    number = int(input("Enter your number >> "))
    p1, p2 = goldbach_keep_index(number)
    print(f"{p1} + {p2} = {number}")

However, what you are really doing is taking all combinations of prime numbers, without repeating yourself. So just use itertools.combinations_with_replacement:

from itertools import combinations_with_replacement

def goldbach_combinations(number):
    if number % 2 == 0:
        raise ValueError("Goldbach conjecture is only defined for even numbers")
    primes = primenums(number)
    for addend1, addend2 in combinations_with_replacement(primes, 2):
        if addend1 + addend2 == number:
            return addend1, addend2
    raise Exception(f"Found a counter-example to the Goldbach conjecture: {number}")

In this case primes does not even need to be a list, it can just be a generator.

If you instead make primes a set, you can easily implement the idea suggested by @Josiah in their answer by just checking if number - p is in primes:

def goldbach_set(number):
    if number % 2 == 0: #Only even numbers
        raise ValueError("Goldbach conjecture is only defined for even numbers")
    primes = set(primenums(number)) #returns all prime numbers <= input number
    for p in primes:
        k = number - p
        if k in primes:
            return p, k
    raise Exception(f"Found a counter-example to the Goldbach conjecture: {number}")

And now some timing comparisons, where goldbach is your code put into a function:

def goldbach(number):
    if number % 2 == 0: #Only even numbers
        raise ValueError("Goldbach conjecture is only defined for even numbers")
    primes = primenums(number) #returns all prime numbers <= input number
    addend1 = primes[0]
    addend2 = primes[0]

    while addend1 + addend2 != number:
        if primes[-1] == addend2:
            addend2 = primes[primes.index(addend1) + 1]
            addend1 = primes[primes.index(addend1) + 1]
        else:
            addend2 = primes[primes.index(addend2) + 1]
    return addend1, addend2

And primenums is a simple sieve:

def prime_sieve(limit):
    prime = [True] * limit
    prime[0] = prime[1] = False

    for i, is_prime in enumerate(prime):
        if is_prime:
            yield i
            for n in range(i * i, limit, i):
                prime[n] = False

def primenums(limit):
    return list(prime_sieve(limit))

And when pulling the generation of the primes outside of the function (and calculating them up to the largest number in the plot):

Of course the first three functions are vastly slower than the set because they need to go through more combinations now. However, all functions are then constant time, so the increase in time comes solely from the fact that you have to consider more primes.


Boiler.js Deep Object Comparison Code/Performance Optimizations? I have a deep equality comparison method that returns true when two objects are equal (see method Doc):

_.isEqual = function (obj1, obj2) {

  // Quick compare objects that don't have nested objects
  if (_.type(obj1) === _.type(obj2) && !_.isPlainObject(obj1) && !_.isArray(obj1)) {
    switch (_.type(obj1)) {
      case "function" :
        if (obj1.toString() !== obj2.toString()) return false;
        break;
      case "nan" :
        if (obj1 === obj2) return false;
        break;
      default:
        if (obj1 !== obj2) return false;
    }
  } else {

    // When target or comparison is falsy we compare them directly
    if (_.isFalsy(obj1) || _.isFalsy(obj2)) {
      if (obj1 !== obj2) return false;
    }
    for (var o in obj1) {
      switch (true) {

        // Catch comparison of element first to prevent infinite loop when caught as objects
        case ( _.isElement(obj1[o]) ) :
          if (obj1[o] !== obj2[o]) return false;
          break;
        case ( _.isNaN(obj1[o]) ) :
          if (!_.isNaN(obj2[o])) return false;
          break;
        case ( typeof obj1[o] === "object" ) :
          if (!_.isEqual(obj1[o], obj2[o])) return false;
          break;
        case ( typeof obj1[o] === "function" ) :
          if (!_.isFunction(obj2[o])) return false;
          if (obj1[o].toString() !== obj2[o].toString()) return false;
          break;
        default :
          if (obj1[o] !== obj2[o]) return false;
      }
    }

    // Reverse comparison of `obj2`
    for (var o in obj2) {
      if (typeof obj1 === "undefined") return false;
      if (obj1 === null || obj1 === undefined) return false;
      if (_.isFalsy(obj1[o])) {
        if (_.isNaN(obj1[o])) {
          if (!_.isNaN(obj2[o])) return false;
        } else if (obj1[o] !== obj2[o]) return false;
      }
    }
  }
  return true;
};

I'm looking for advice on strategies I can use to improve its performance. My initial thoughts are get rid of my calls to internal library methods? Should I implement a different type of loop. Would a while lead to any performance gains?

After taking much of what @Joseph the Dreamer said into account I refactored _.isEqual in a seemingly much more efficient manner, which now compares the properties and values that might be attached to functions as well. As you can see I did away with a great many of my previous comparisons because they're rendered redundant in this iteration (I believe).

Here are the unit tests to back this method up: _.isEqual Unit Tests

The code:

_.isEqual = function (obj1, obj2) {
  var type = _.type(obj1), result, o;

  switch (true) {

    // Not the same TYPE
    case type != _.type(obj2) :
      return false;

    // NaNs
    case type == 'nan' :
      return _.isNaN(obj1) && _.isNaN(obj2);

    // Primitives (types that will compare correctly with ===)
    case ((typeof obj1 != 'object' && type != 'function') || type == 'null') :
      return obj1 === obj2;

    // Functions or Elements
    case type == 'function' || type == 'element' :
      return obj1.constructor === obj2.constructor;

    // JavaScript Objects
    default :
      if (_.len(obj1) == 0) {
        result = _.len(obj2) == 0;
      } else {
        for (o in obj1) {
          if (!(result = _.isEqual(obj1[o], obj2[o]))) break;
        }
      }
  }

  return result;
};

After going through the code and the library itself, here are some thoughts:

Functions are still objects. You can even attach properties to it. You might want to look into this unless you only want to compare the function, excluding the things attached to it.

function foo(){};
foo.bar = 'baz';
console.log(foo.bar); //baz

Early on, you can weed out values that are equal or actually the same to avoid going through everything. Equal strings, numbers, booleans and even objects in general (Since they are compared by identity) return true.

obj1 === obj2

If this returns false, it could be that the values are non-equal primitives, or non-identical objects. You can return false for the primitives. For objects in general, only then will you do the "structure equality check".
Comparisons return a boolean value. So if you return a boolean after a comparison without doing anything else after, you can shorten the statement.

/*from*/ if(a !== b) return false;
/* to */ return a === b;

While for(var o in obj1) is perfectly valid JS, it's something you'd look out for. You actually did this twice in the code. If you pass your code through a linter, you'd get a o already defined error. Do this instead

var o;

for(o in obj1){...}
...
for(o in obj2){...}

Or better, just use another variable name instead of o on the second loop.
You seem to already have a lot of abstractions in your library, which is good. However, your code seems to use a mix of abstracted and vanilla code. I suggest using your abstracted code so that in case the approach for a certain operation is wrong, you only need to modify the abstracted version.

jQuery actually does this. It keeps a "Core API" which is used by the other parts of the source. If you look at their source, each and extend are used quite a lot.
null and undefined are already falsy values. Assuming you already weeded out other values for obj1, you could already simplify.

if(typeof obj1 === "undefined") return false;
if(obj1 === null || obj1 === undefined) return false;

//to

if(!obj1) return false;
//or
if(_.isFalsy(obj1)) return false;


arithmetic with numbers and letters I've started learning JavaScript last week. Today I ran into a JS exercise available at this link
codewars exercise and decided to give it a try. I've used very basic JS because I know only a small number of JS methods. Could you please review and rate my code?

challenge text :

  Your task is to write a function named do_math that receives a single argument. This argument is a string that contains multiple whitespace delimited numbers. Each number has a single alphabet letter somewhere within it.

    Example : "24z6 1x23 y369 89a 900b"

  As shown above, this alphabet letter can appear anywhere within the number. You have to extract the letters and sort the numbers according to their corresponding letters.

    Example : "24z6 1x23 y369 89a 900b" will become 89 900 123 369 246 (ordered according to the alphabet letter)

  Here comes the difficult part, now you have to do a series of computations on the numbers you have extracted.

  The sequence of computations are + - * /. Basic math rules do NOT apply, you have to do each computation in exactly this order.
  This has to work for any size of numbers sent in (after division, go back to addition, etc).
  In the case of duplicate alphabet letters, you have to arrange them according to the number that appeared first in the input string.
  Remember to also round the final answer to the nearest integer.

    Examples :
        "24z6 1x23 y369 89a 900b" = 89 + 900 - 123 * 369 / 246 = 1299
        "24z6 1z23 y369 89z 900b" = 900 + 369 - 246 * 123 / 89 = 1414
        "10a 90x 14b 78u 45a 7b 34y" = 10 + 45 - 14 * 7 / 78 + 90 - 34 = 60

my code :

var inputStr, inputsArray, numsArray, arrayStrNumber, isAdd, isSub, isMul, isDiv;

numsArray = [];
strArray = [];
arrayStrNumber = [];
inputStr = "10a 90x 14b 78u 45a 7b 34y";

isAdd = true;
isSub = true;
isMul = true;
isDiv = true;

// create array from strings
inputsArray = inputStr.split(" ");

// loop in array

for (var i = 0; i < inputsArray.length; i++) {
  var inputValue = inputsArray[i];

  // seperate numbers from alphabet
  for (x = 0; x < inputValue.length; x++) {

    //   if it's not a number add it to string's array
    if (isNaN(inputValue[x])) {
      strArray[i] = inputValue[x];
    } else {
      isNaN(numsArray[i])
        ? (numsArray[i] = "" + inputValue[x] + "")
        : (numsArray[i] += "" + inputValue[x] + "");
    }
  }

  //create an array with letter on start
  arrayStrNumber[i] = strArray[i] + numsArray[i];
}
// sort array based on first alphabet or first number after alphabet
arrayStrNumber.sort(function (a, b) {
  if (a[0] != b[0]) {
    if (a > b) {
      return 1;
    }
    if (b > a) {
      return -1;
    }
    return 0;
  } else {
    if (arrayStrNumber.indexOf(a) > arrayStrNumber.indexOf(b)) {
      return 1;
    }
    if (arrayStrNumber.indexOf(b) > arrayStrNumber.indexOf(a)) {
      return -1;
    }
    return 0;
  }
});

console.log(arrayStrNumber);
// Do math operation with order +-*/
var finalResult = 0;
for (var i = 0; i < arrayStrNumber.length; i++) {
  arrayStrNumber[i] = parseInt(arrayStrNumber[i].slice(1));
  if (i === 0) {
    finalResult += arrayStrNumber[i];
    continue;
  }
  if (isAdd) {
    finalResult += arrayStrNumber[i];
    isAdd = false;
    continue;
  }
  if (isSub) {
    finalResult -= arrayStrNumber[i];
    isSub = false;
    continue;
  }
  if (isMul) {
    finalResult *= arrayStrNumber[i];
    isMul = false;
    continue;
  }
  if (isDiv) {
    finalResult /= arrayStrNumber[i];
  }
  isAdd = true;
  isSub = true;
  isMul = true;
  isDiv = true;
  finalResult = Math.round(finalResult);
}

When writing maintainable code, I'd recommend to declare variables in narrow scopes, if possible. If you do something like:

var inputStr, inputsArray, numsArray, arrayStrNumber, isAdd, isSub, isMul, isDiv;

at the very beginning, then on every line throughout the rest of the program, you'll have to keep in mind the possible values for all of those variables. If the script is long, this can be a problem. Consider encapsulating related functionality into separate functions instead - for example, you could turn the input into an array in one function, sort it in another, and then finally iterate through it to produce the result in a third. That way, for example, inputStr will only be visible to the first function (as an argument), and neither of the first two functions will have isAdd etc visible to them. Separating functionality into smaller self-contained sections makes code a lot more readable.

Since it's 2020, it would be nice to write source code in modern syntax - at least in ES2015. Modern syntax generally makes code more concise, easier to read, and less buggy. (I'll be using modern syntax in suggestions below.)

Consider always using strict mode - you have some variables that you never declare (strArray and x), which means that they get implicitly assigned to the global object. This is an easy source of bugs, not to mention inelegant; strict mode will throw an error when this sort of thing happens, allowing you to fix it on sight.

When you have to iterate over an array or a string, it's nice to be able to immediately work with each item being iterated over immediately, rather than having to mess with indicies. Both strings and arrays have iterators (which iterate over either each character, or each array item), so you can do this concisely with for..of. For example:

for (let i = 0; i < inputsArray.length; i++) {
  const inputValue = inputsArray[i];

can be replaced with

for (const inputValue of inputsArray) {

You do

isNaN(numsArray[i]) ?
  (numsArray[i] = "" + inputValue[x] + "") :
  (numsArray[i] += "" + inputValue[x] + "");

The conditional operator should only be used when you need an expression which is identified conditionally, like console.log(cond ? '1' : '2'). If the expression that results from using the conditional operator isn't being used, like in your code, it would be more readable to remove it and use if/else instead. (It's fine for minifiers to do that, but minified code isn't intended to be read - source code that developers write should be as readable as possible). There's even a linting rule to help you automatically identify and fix this sort of thing.

So, you have a string which is composed of numbers, plus one letter somewhere inside it, and you need to separate them. If you want to do this concisely, you might consider using replace to replace the letter character with the empty string, and use a callback to assign the matched value (the letter) to an outer variable, like this:

function separateWord(word) {
  let char;
  const num = Number(
    word.replace(
      /[a-z]/i,
      match => {
        char = match;
        return ''; // replace this match with the empty string
      }
    )
  );
  return { char, num };
}
console.log(separateWord('123b456'));

On a broader scale, using the above function, I think the first section of the code which turns each word into a sorted array would be easier to manage if you used an object indexed by character instead, whose values are arrays of numbers. Eg, for the above 123b456, that would result in the following object:

{
  b: [123456]
}

Iterate over each word, pushing to an array on the object, creating it first if necessary. Then, the object properties can be arranged lexiographically by sorting its entries (Object.entries returns an array of entries, where an entry is an array containing the key and the value, so just compare the keys in the .sort). This makes things so much shorter and cleaner:

function getOrderedNumbers(numbersByChar) {
  return Object.entries(numbersByChar)
    .sort((a, b) => (a[0] > b[0]) - 0.5) // Order entries alphabetically
    .map(entry => entry[1]) // Take only the value of each entry
    .flat(); // Turn the array of arrays of numbers into a single array of numbers
}
function parseString(inputStr) {
  const numbersByChar = {};
  for (const word of inputStr.split(' ')) {
    const { char, num } = separateWord(word);
    if (!numbersByChar[char]) {
      numbersByChar[char] = [];
    }
    numbersByChar[char].push(num);
  }
  const numbersArr = getOrderedNumbers(numbersByChar);
  return doMath(numbersArr);
}

For the doMath function, keeping track of 4 separate booleans and performing 4 different if checks is a bit verbose for the task at hand. You might consider using an array of functions instead, and using the modulo operator to identify which function to call:

function doMath(numbersArr) {
  const fns = [
    (subtotal, num) => subtotal + num,
    (subtotal, num) => subtotal - num,
    (subtotal, num) => subtotal * num,
    (subtotal, num) => subtotal / num,
  ];
  // Remove first value so operation can start with + with first and second value:
  let subtotal = numbersArr.shift();
  numbersArr.forEach((num, i) => {
    subtotal = fns[i % 4](subtotal, num);
  });
  return subtotal;
}
console.log(doMath([1, 2, 4, 5])); // ((1 + 2) - 4) * 5

reduce would be more appropriate than forEach to transform the array of numbers into a single number, but if you're a beginner, you probably prefer the forEach version since it's more intuitive:

function doMath(numbersArr) {
  const fns = [
    (subtotal, num) => subtotal + num,
    (subtotal, num) => subtotal - num,
    (subtotal, num) => subtotal * num,
    (subtotal, num) => subtotal / num,
  ];
  // Remove first value so operation can start with + with first and second value:
  const initialValue = numbersArr.shift();
  return numbersArr.reduce((subtotal, num, i) => fns[i % 4](subtotal, num), initialValue);
}
console.log(doMath([1, 2, 4, 5])); // ((1 + 2) - 4) * 5

Put it all together:

'use strict';

console.log(doMath("10a 90x 14b 78u 45a 7b 34y"));

function separateWord(word) {
  let char;
  const num = Number(
    word.replace(
      /[a-z]/i,
      match => {
        char = match;
        return ''; // replace this match with the empty string
      }
    )
  );
  return { char, num };
}
function getOrderedNumbers(numbersByChar) {
  return Object.entries(numbersByChar)
    .sort((a, b) => (a[0] > b[0]) - 0.5) // Order entries alphabetically
    .map(entry => entry[1]) // Take only the value of each entry
    .flat(); // Turn the array of arrays of numbers into a single array of numbers
}
// Entry point:
function doMath(inputStr) {
  const numbersByChar = {};
  for (const word of inputStr.split(' ')) {
    const { char, num } = separateWord(word);
    if (!numbersByChar[char]) {
      numbersByChar[char] = [];
    }
    numbersByChar[char].push(num);
  }
  const numbersArr = getOrderedNumbers(numbersByChar);
  return getTotal(numbersArr);
}

function getTotal(numbersArr) {
  const fns = [
    (subtotal, num) => subtotal + num,
    (subtotal, num) => subtotal - num,
    (subtotal, num) => subtotal * num,
    (subtotal, num) => subtotal / num,
  ];
  // Remove first value so operation can start with + with first and second value:
  let subtotal = numbersArr.shift();
  numbersArr.forEach((num, i) => {
    subtotal = fns[i % 4](subtotal, num);
  });
  return Math.round(subtotal);
}

Unfortunately, the latest JS version that Codewars supports is Node 8, which is old, end-of-life, and probably shouldn't be used - it doesn't support Array.prototype.flat. An alternative to achieve the same functionality is to spread into concat instead:

arr.flat()

can be replaced by

[].concat(...arr);


Correct use of MVVM and MouseEvent Handling My XAML looksl ike this:

<UserControl x:Class="Dexel.Editor.Views.UI_Sketches.UiSketchCanvas"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:cc="clr-namespace:Dexel.Editor.Views.CustomControls"
         xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
         xmlns:command="http://www.galasoft.ch/mvvmlight"
         mc:Ignorable="d"
    Background="{DynamicResource  BG}">
<Grid>
<ItemsControl ItemsSource="{Binding Rectangles}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="PreviewMouseLeftButtonDown">
                <command:EventToCommand Command="{Binding mouseTestCommand}" PassEventArgsToCommand="True"/>
        </i:EventTrigger >
    </i:Interaction.Triggers>
        <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas Background="Transparent"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemContainerStyle>
        <Style TargetType="ContentPresenter">
            <Setter Property="Canvas.Left" Value="{Binding X}"></Setter>
            <Setter Property="Canvas.Top" Value="{Binding Y}"></Setter>
        </Style>
    </ItemsControl.ItemContainerStyle>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
                <Rectangle Width="{Binding Width}" Height="{Binding Height}" Fill="Transparent" Stroke="White">
                </Rectangle>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>

In my ViewModel I have this code to handle the command:

public ICommand MouseTestCommand
    {
        get
        {
            if (_mouseTestCommand == null)
            {
                _mouseTestCommand = new CommandBase(eventArgs => mouseTest(eventArgs), null);
            }
            return _mouseTestCommand;
        }
    }

which calls this function:

private void MouseTest(object eventArgs)
    {
        var test = (MouseButtonEventArgs)eventArgs;
        var source = (Rectangle)test.OriginalSource;
        var rectangle = source.DataContext as SketchRectangleViewModel;
        Selected = rectangle;

    }

Is the implementation I use right now even MVVM? If so is the code I use right now bad? I'm not sure if there is a better way but I somehow have to get the information where the user clicked and recieve the DataContext if it is an rectangle.

Problems I see already:

Somehow need to check that the recieved original source is actually a rectangle and not the canvas

Looks OK to me. You do leak views to your viewmodel though. Some better approaches:

Handle event on rectangle itself. It will allow you to bind it's DataContext directly to command parameter. This should eliminate the leak.
Use items control that supports selection, i.e. ListBox. Then you will be able to bind to SelectedItem property directly without any events.

Other minor things:

Base postfix is normally used to indicate an abstract class. Might want to remove it from your command class, since it is clearly not abstract.
I'm not sure where this whole thing with lazy initialization is coming from (it is not the first time I see it), but it makes no sense to me. What's the point in lazy initialization for commands? Just use regular readonly property:

public ICommand MouseTestCommand {get;}

And initialize it in constructor. It is cleaner and requires less code to write. Also you might want to create another constructor for your command, that passes null for CanExecute by default.


Is there anything can be improved in this JavaScript module? I am using RequireJS JavaScript library. I have the following JavaScript module define for dataservice:

define(['jquery'], function ($) {

    var callApi = function (url, type, dataType, data, callback) {
        $.ajax({
            url: url,
            type: type,
            data: data,
            dataType: dataType,
            contentType: "application/json",
            success: function (data) {
                callback(data);
            }
        });
    };

    var getData = function (url, dataType, data, callback) {
        callApi(url, 'GET', dataType, data, callback);
    };

    var postData = function (url, data, callback) {
        callApi(url, 'POST', 'json', data, callback)
    };

    return {
        getData: getData,
        postData: postData
    };

});

Is there anything which can be improved in this module?

I really like this code.

Still, 2 observations:

The code is awfully optimistic, no default error handling ?
success gets data, textStatus, and jqXHR. I would pass all 3 to the callback function.


Codewars - Highest Scoring Word Here is my solution for CodeWars - Highest Scoring Game

  Given a string of words, you need to find the highest scoring word.

  Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.

  You need to return the highest scoring word as a string.

  If two words score the same, return the word that appears earliest in the original string.

  All letters will be lowercase and all inputs will be valid

  Example:

  Input: 'man i need a taxi up to ubud'

  Output: 'taxi'

This is my solution:

def word_value(input_word):
      values = {
        'a': 1,
        'b': 2,
        'c': 3,
        'd': 4,
        'e': 5,
        'f': 6,
        'g': 7,
        'h': 8,
        'i': 9,
        'j': 10,
        'k': 11,
        'l': 12,
        'm': 13,
        'n': 14,
        'o': 15,
        'p': 16,
        'q': 17,
        'r': 18,
        's': 19,
        't': 20,
        'u': 21,
        'v': 22,
        'w': 23,
        'x': 24,
        'y': 25,
        'z': 26
      }
      value = 0
      for letter in input_word:
          value += values[letter]
      return value

def high(x):
    word_list = x.split(" ")

    word_values = []
    for word in word_list:
        word_values.append(word_value(word))

    max_value = max(word_values)
    index_of_max = word_values.index(max_value)

    return word_list[index_of_max]

The solution passed the test suite but I think I can improve the part where I store all the letters matched with their value. Is there any suggestions for this and in general the entire code?

Thank you.

Indeed, the values dictionary looks unnecessary. Using a built-in function ord you could compute the letter score with ord(letter) - ord('a') + 1. One may argue that it is even faster than a dictionary lookup, but in this case the timing difference is rather marginal.

With Python you should avoid rolling explicit loops. For example, collecting the word values is more idiomatically expressed as a comprehension:

    word_values = [word_value(word) for word in word_list]

Similarly, instead of

    for letter in input_word:
        value += values[letter]

consider functools.reduce:

    value = functools.reduce(lambda x, y: x + ord(y) - ord('a') + 1, input_word, 0)


Tic Tac Toe in C++14 I've decided to learn C++, coming from Python, and this is my first program. I would love some feedback on it.

It's split up into two header files and one .cpp file:

Board.h

class Board {

public:

    std::string board[7][4] = {
        { "\n\n-------------\n" },
        { "| 1 ", "| 2 ",  "| 3 ", "|\n" },
        { "----+---+----\n" },
        { "| 4 ", "| 5 ",  "| 6 ", "|\n" },
        { "----+---+----\n" },
        { "| 7 ", "| 8 ",  "| 9 ", "|\n" },
        { "-------------\n" }
    };

    void displayBoard(); // Displays the board[2D Array]

} board;

void Board::displayBoard()
{
    for (int x = 0; x < 7; x++) // Row of the 2D array
        for (int i = 0; i < 4; i++) // Column of the 2D array
            std::cout << board[x][i];
}

Player.h

class Player {

private:

    int in, row, col;
    std::string peice, player;

public:

    Player(std::string x); // Sets up peice, depending on parameter
    int move();           // Gets input and makes move
    bool winner();       // Checks for winner

} p1("X"), p2("O");

// CLASS FUNCTIONS

Player::Player(std::string x)
{
    player = x;
    peice = player == "X" ? "| X " : "| O ";
}

int Player::move()
{
beginning:

    while (!(in > 0 && in < 10)) // Only accpets values between 1-9
    {
        std::cout << "\nPlayer " << player << " enter position: ";
        std::cin >> in;
    }

    row = in > 3 && in < 7 ? 3 : 1;                    // Sets row
    row = in > 6 && in < 10 ? 5 : row;

    col = in == 2 || in == 5 || in == 8 ? 1 : 0;       // Sets Column
    col = in == 3 || in == 6 || in == 9 ? 2 : col;

    in = 0; // Sets back to 0 so the while expression will work again

    if (board.board[row][col] == "| X " || board.board[row][col] == "| O ")
    { // If space has already been taken, ask for input again
        goto beginning;
    }

    board.board[row][col] = peice;  // Convert position from board into the peice
    system("cls");                 // Clears everything in the window
    board.displayBoard();         // Display Board

    if (winner() == true) { return 1; } // Checks if this player has won
}

bool Player::winner()
{
    for (int x = 1; x < 6; x += 2)
    {
        if (board.board[x][0] == peice && board.board[x][1] == peice && board.board[x][2] == peice || // Horizontal
            board.board[1][x - 1] == peice && board.board[3][x - 1] == peice && board.board[5][x - 1] == peice || // Verical
            board.board[1][x - 1] == peice && board.board[3][1] == peice && board.board[5][x == 1 ? 2 : 0] == peice) // Diagonal
        {
            std::cout << "\nPlayer " << player << " has won\n";
            return true;
        }
    }
}

TicTacToe.cpp

// Tic Tac Toe - TCG

#include <iostream>
#include <string>

#include "Board.h"
#include "Player.h"

int main()
{
    std::cout << "Welcome to Tic Tac Toe";
    board.displayBoard();

    for (int x = 0; x < 6; x++)
    {
        if (p1.move() == 1) { break; } // Player X

        if (x == 4) // If there is no winner up until the end of the game; end game
        {
            std::cout << "\n\n\nThe match was a draw\n";
            break;
        }

        if (p2.move() == 1) { break; } // Player O
    }
}

Here is the program compiled and running:

Welcome to Tic Tac Toe

-------------
| 1 | 2 | 3 |
----+---+----
| 4 | 5 | 6 |
----+---+----
| 7 | 8 | 9 |
-------------

Player X enter position:

Here is the updated version.

Here are some observations and suggestions that may help you improve your program.

Check your spelling

If you run a spell check on your comments, you'll find a number of things such as "peice" instead of "piece" and "accpets" instead of "accepts".  Since your code is nicely commented, it's worth the extra step to eliminate spelling errors.

Separate interface from implementation

The interface goes into a header file and the implementation (that is, everything that actually emits bytes including all functions and data) should be in a separate .cpp file.  The reason is that you might have multiple source files including the .h file but only one instance of the corresponding .cpp file.  In other words, split your existing Player.h file into a Player.h file and a Player.cpp file and do the same with Board.h.

Always return an appropriate value

Your Player::move() routine has control paths that cause it to end without returning any int value.  This is an error and should be fixed.

Don't use system("cls")

There are two reasons not to use system("cls") or system("pause").  The first is that it is not portable to other operating systems which you may or may not care about now.  The second is that it's a security hole, which you absolutely must care about.  Specifically, if some program is defined and named cls or pause, your program will execute that program instead of what you intend, and that other program could be anything.  First, isolate these into a seperate functions cls() and pause() and then modify your code to call those functions instead of system.  Then rewrite the contents of those functions to do what you want using C++.  For example, if your terminal supports ANSI Escape sequences, you could use this:

void cls()
{
    std::cout << "\x1b[2J";
}

Use appropriate #includes

The Player class uses a std::string as part of its interface, but there are no #includes in that file.  Each file should have only and exactly the required #includes.  In this case, it needs #include <string> within the header.

Eliminate "magic numbers"

In a number of cases, the code uses "magic numbers" such as 10 and 6 that have no obvious meaning.  These would be better as named constants if they're used more than once.

Avoid the use of global variables

In this code p1, p2 and board are all global variables. It's generally better to explicitly pass variables your function will need or declare them within the appropriately smallest possible scope rather than using the vague implicit linkage of a global variable.  For example, the main function could instead have three local variables like this:

Board board;
Player p1("X");
Player p2("O");

If the Player member functions need access to the board, then pass a reference to the board as needed.  For example:

p1.move(board)

Use include guards

There should be an include guard in each .h file.  That is, start the file with:

#ifndef BOARD_H
#define BOARD_H
// file contents go here
#endif // BOARD_H

Fix the bug

The way it's currently written, if player 1 wins by getting all the spaces in the middle column, it is not recognized by the program as a win.  I'll leave it to you to figure out what's wrong and fix it.

Simplify expressions

The Player code currently contains this line:

if (winner() == true) { return 1; } // Checks if this player has won

This has three problems.  First, as mentioned above, the function should also return something if the expression is false.  Second, if the return from the move function is interpreted as a binary value, the function should be declared as returning bool rather than int.  Third, this can be simplifed to this:

return winner(board);

Which takes care of all three problems and also assumes that the function has been modified to pass board instead of using a global.

Use const where practical

In the Board::display routine, the underlying Board is not altered.  Make this explicit by declaring that routine const as:

void displayBoard() const; // Displays the board[2D Array]

Rethink your class design

The Player classes freely access the internals of the Board class and the Board class member data is public, meaning that any code can modify it.  That's not good object design.  Better would be to think clearly about the separation between the Board and Player objects and to provide a clean separation and interface between the two.

Separate responsibilities

The Model-View-Controller design pattern is often useful for programs like this.  Because the view in this case is essentially just printing the board to std::cout, we can simplify a bit and just have a model, the Board class, and perhaps a pair of controllers, the Player class.

Use meaningful variable names

Your Board and Player class are descriptive and good enough, but the variable names are not so good.  In particular the x variable in main is not at all descriptive of the content.  A better name might be moveCount.

Declare the loop exit condition at the top

The for loop inside main currently says this:

for (int x = 0; x < 6; x++)

Reading that line, we would conclude that the play continues until x >= 6.  However, within the loop is are three breaks that occurs if one player has won or if it's a draw.  Rather than forcing the reader of the code to examine every line, it's better if you simply declare loop exit conditions completely and honestly at the top.

while (!board.full() && !p1.move(board) && !p2.move(board)) {
    // play until either draw or one player wins
}

Avoid using goto

Having a proliferation of goto statements is usually a sign of bad design.  Better would be to eliminate them entirely -- it makes the code easier to follow and less error-prone.  In this code, you could very easily use a loop instead:

do {
    // try to apply the move
} while (board.board[row][col] == "| X " || board.board[row][col] == "| O ");

Separate I/O from logic

The Player::move routine prints a prompt, gets input from the user and then applies that to the board.  It would be better to separate I/O from the game logic so that the game is cleanly separated from the I/O.  This would, for example, make it much easier to convert the game into a GUI version.

Use a better data structure

The Board class uses an array of printable strings as its data member.  There's nothing inherently wrong with this, but that only simplifies the printing of the board at the expense of every other use.  Instead, choose a more natural data structure, such as a 3x3 array, and you'll find that the calculations are much easier to write correctly.


Print a list of strings in assembly How does the following program look to print a list of strings? What places can I improve? Are there easier ways to print something like a linebreak after each string rather than hardcoding the \n into the string itself?
# Program, print out a list of strings, one per line
.data

SYS_EXIT   = 60
SYS_WRITE  = 1
SYS_STDOUT = 1

# Empty string means end of strings
strings:    .asciz  "Once\n", "upon\n", "a\n", "time\n", "...\n", ""

.text
.globl _start

get_string_length:
    mov $0, %eax
  .L1_loop:
    movzbl (%edi, %eax), %ecx
    cmp $0, %cl
    je .L1_exit
    inc %eax
    jmp .L1_loop
  .L1_exit:
    ret

_start:

    mov $strings,   %rbx
  print_loop:
    mov %rbx,       %rdi
    call get_string_length # (rdi=file_descriptor, rsi=starting_address, rdx=size)
    cmp $0, %eax
    jz exit
    mov $SYS_STDOUT,%edi
    mov %rbx,       %rsi
    mov %eax,       %edx
    mov $SYS_WRITE, %eax
    syscall
    lea 1(%eax, %ebx,), %ebx
    jmp print_loop

  exit:
    mov $0,        %edi
    mov $SYS_EXIT, %eax
    syscall

Are there easier ways to print something like a linebreak after each string rather than hardcoding the \n into the string itself?

Embedded newlines are certainly the easiest way to do this, but definitively not the most versatile way. Embedding the newlines kind of pushes you in the direction that  the strings will be used for outputting only. You might want to do lots of other stuff with them too.
I advocate keeping the strings pure and adding the linebreaks, or any other prefix or suffix for that matter, later on. Since you already have to count the characters in the string, you can at the same time copy the string to a buffer (every non-trivial program has some general purpose buffer at the ready). Once you read the zero terminator you store the newline in the buffer. Then you're ready to print the buffer contents for which you now know the length.
In below code PrepStringForOutput is a leaf function which means you can do pretty much anything you like in it. You don't have to follow any register conventions per se.
# Program, print out a list of strings, one per line
.data

SYS_EXIT   = 60
SYS_WRITE  = 1
SYS_STDOUT = 1

# Empty string means end of strings
Strings:    .asciz  "Once", "upon", "a", "time", "...", ""
Buffer:     .ascii  "12345"

.text
.globl _start

; IN (%rbx is asciz) OUT (%rsi is buffer, %rdx is length) MOD (%al)

PrepStringForOutput:
    mov     $Buffer, %rsi        # Destination
    xor     %edx, %edx           # Length
  .L1_loop:
    mov     (%rbx, %rdx), %al    # Character from asciz string
    test    %al, %al
    jz      .L1_exit
    mov     %al, (%rsi, %rdx)    # Store in buffer
    inc     %edx
    jmp     .L1_loop
  .L1_exit:
    mov     $10, (%rsi, %rdx)    # Adding newline
    inc     %edx
    ret

_start:

    mov     $Strings, %rbx
  PrintLoop:
    cmpb    $0, (%rbx)           # End of list ?
    je      Exit
    call    PrepStringForOutput  # -> %rsi is address, %rdx is length
    add     %rdx, %rbx           # Advancing in the list
    mov     $SYS_STDOUT, %edi
    mov     $SYS_WRITE, %eax
    syscall
    jmp     PrintLoop
  Exit:
    xor     %edi, %edi
    mov     $SYS_EXIT, %eax
    syscall

What places can I improve?

You'll easily spot these in above code...
See the nice tabular layout?


Series, Powers, and Benches Project Euler problem 48

  The series, \$1^1 + 2^2 + 3^3 + ... + 10^{10} = 10405071317\$.

  Find the last ten digits of the series, \$1^1 + 2^2 + 3^3 + ... + 1000^{1000}\$.

I made two different implementations of this problem, and added a benchmark, using rolfl's UBench library.

The code:

public class ProjEuler48 {

    private static final int DIGITS = 10;
    private static final BigInteger MOD = BigInteger.TEN.pow(DIGITS);

    public static void main(String[] args) {
        final int max = 1000;
        UBench bench = new UBench(ProjEuler48.class.getSimpleName());
        Predicate<BigInteger> predicate = value -> value.longValue() == 9110846700L;
        bench.addTask("Loops", () -> selfPowerSumMod(max, MOD), predicate);
        bench.addTask("Streams", () -> selfPowerSumModStreams(max, MOD), predicate);
        bench.report("RESULTS", bench.press(1000));
    }

    private static BigInteger selfPowerSumModStreams(int max, BigInteger mod) {
        return IntStream.rangeClosed(1, max)
                .parallel()
                .mapToObj(i -> BigInteger.valueOf(i))
                .map(bi -> bi.modPow(bi, MOD))
                .reduce(BigInteger.ZERO, BigInteger::add, BigInteger::add)
                .mod(mod);
    }

    public static BigInteger selfPowerSumMod(int max, BigInteger mod) {
        BigInteger sum = BigInteger.ZERO;
        for (int i = 1; i <= max; i++) {
            sum = sum.add(selfPower(i)).mod(mod);
        }
        return sum;
    }

    public static BigInteger selfPower(int i) {
        BigInteger result = BigInteger.valueOf(i);
        return result.modPow(result, MOD);
    }

}

Benchmark results on my machine:

RESULTS
=======

Task ProjEuler48 -> Loops: (Unit: MILLISECONDS)
  Count    :     1000      Average  :   2.5267
  Fastest  :   2.0137      Slowest  :  35.8331
  95Pctile :   4.2812      99Pctile :   8.3346
  TimeBlock : 4.718 2.646 2.801 2.280 2.191 2.128 2.119 2.124 2.132 2.127
  Histogram :   936    53    10     0     1

Task ProjEuler48 -> Streams: (Unit: MILLISECONDS)
  Count    :     1000      Average  :   0.8798
  Fastest  :   0.3701      Slowest  :  37.6239
  95Pctile :   2.7441      99Pctile :   5.5763
  TimeBlock : 3.032 1.041 1.285 0.596 0.476 0.485 0.467 0.473 0.464 0.479
  Histogram :   802    75    86    27     9     0     1

How is this code in terms of Project Euler, Java 8, performance and everything?

This looks pretty good. A few changes I would make:
Performance
10^10, 20^20, and all higher powers will always end in 0000000000, which means they don't affect the sum. You should be able to get an approximately 10% performance improvement by not computing these powers. This would be easy to do in your loops case but would require a little syntactical cleverness in the streams way.
Magic Numbers
You have a magic number 9110846700L in your code. It's not immediately clear what this is, especially if you are unfamiliar with the UBench library. This should be refactored into a magic number constant, in this case. Further reading on this subject
Static methods
Even for a program as simple as this, I would always shy away from putting your business logic in static methods. Obviously, in this case it isn't a problem, but for an application could grow at all, you will quickly regret it. More further reading
Inconsistent method scope
One of your methods is private, the others are public. Again, this issue is not super relevant for such a short program, but allowing encapsulation to be broken starts to matter as soon a program reaches two classes.


Looping through Files in a Folder I have this simple looping macro, but I can't seem how to figure out how to make it run faster. I tried including more update = false statements as well as well as removing any selecting type behavior.

 Sub AbesLoop()

 Dim wbk As Workbook
 Dim ws As Integer
 Dim Filename As String
 Dim Path As String
 Dim rCell As Range
 Dim rRng As Range
 Dim wsO As Worksheet

 Application.ScreenUpdating = False
 Application.DisplayAlerts = False
 Application.Calculation = xlCalculationManual

 Path = "PathToFolder" & "\"
 Filename = Dir(Path & "*.xl??")
 Set wsO = ThisWorkbook.Sheets("Sheet1")

 Do While Len(Filename) > 0
     Set wbk = Workbooks.Open(Path & Filename, True, True)
     ws = wbk.Worksheets.Count
     For i = 1 To ws
     Application.ScreenUpdating = False
     Application.DisplayAlerts = False
     Application.Calculation = xlCalculationManual
     Set rRng = Range("b1:b20")
         For Each rCell In rRng.Cells
             If rCell <> "" And rCell.Value <> "Not Tested" Then

             wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(1, 0).Value = rCell
             wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 1).Value = rCell.Offset(0, -1)
             wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 2).Value = Right(ActiveWorkbook.FullName, 15)
             End If
         Next rCell
     Next i
     wbk.Close False
     Filename = Dir
 Loop

 Application.ScreenUpdating = True
 Application.DisplayAlerts = True
 Application.Calculation = xlCalculationAutomatic

 End Sub

This answer is just going to focus on what you asked for, how to speed up your code. I'm going to go through line by line and note anything that could be done to make it faster.

 Application.ScreenUpdating = False
 Application.DisplayAlerts = False
 Application.Calculation = xlCalculationManual

 Path = "PathToFolder" & "\"
 Filename = Dir(Path & "*.xl??")
 Set wsO = ThisWorkbook.Sheets("Sheet1")

You might want to add Application.EnableEvents = False.
Other than that, nothing to change here, this is about as fast as it's ever going to get.

Do While Len(Filename) > 0
     Set wbk = Workbooks.Open(Path & Filename, True, True)
     ws = wbk.Worksheets.Count
     For i = 1 To ws
     Application.ScreenUpdating = False
     Application.DisplayAlerts = False
     Application.Calculation = xlCalculationManual
     Set rRng = Range("b1:b20")

This is mostly fine, except why are you re-setting all the Application.Settings options to false? They haven't changed from 6 lines ago. Just cut them out.

An obvious way to speed things up is not to open every worksheet in every workbook in this folder, but I'm going to assume that they are all required.

Opening a workbook does take time. If you've got a lot of them to open, then this macro is going to take time to run no matter how much you optimise it.

     For Each rCell In rRng.Cells
         If rCell <> "" And rCell.Value <> "Not Tested" Then

         wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(1, 0).Value = rCell
         wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 1).Value = rCell.Offset(0, -1)
         wsO.Cells(wsO.Rows.Count, 1).End(xlUp).Offset(0, 2).Value = Right(ActiveWorkbook.FullName, 15)
         End If
     Next rCell

By process of elimination, any performance problems not related to opening the workbooks will be found here.

Fortunately, there are many things to be improved.

My personal #1 rule of fast spreadsheet manipulations:

Thou shalt not directly manipulate data in worksheets

By this I mean, doing anything in a worksheet has huge computational overhead. In the VBA object heirarchy, worksheets are only 2 steps removed from the application object itself. There are layers upon layers of abstractions, events, handlers, objects (not to mention several Billion range objects) buried in a worksheet object, and any time you do something in it, it will trigger a cascade of operations to make sure that nothing in your worksheet gets messed up.

For this reason, you should interact with worksheets as infrequently as possible. If there is data in your worksheet that you need to analyse: access the worksheet once to read the data into an Array, then do all your computations on the Array, then access the worksheet once to read the data back (if applicable).

Your sub then goes like this:

Sub AbesLoop()

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

    Dim targetBook As Workbook
    Dim targetSheet As Worksheet

    Dim sheetCount As Long
    Dim targetFilename As String

    Dim outputSheet As Worksheet
    Set outputSheet = ThisWorkbook.Sheets("Sheet1") '/ Get this out of the way until we need it later

    Dim sheetRange As Range
    '/ Note the *descriptive*, *unambiguous* names.

    '/================================================================================================================================================
    '/================================================================================================================================================
    '/ Create the main array object, define columns, insert headers.

    Dim testOutputData As Variant
    testOutputData = Array()

    Dim testOutputRowIndex As Long
    testOutputRowIndex = 1
    ReDim testOutputData(1 To 3, 1 To testOutputRowIndex) '/ Defined it in a transposed state (column, row) because when extending arrays, if you want to preserve the data, you can only extend the final dimension.

    Const CELL_VALUE_COLUMN As Long = 1
    Const ADJACENT_CELL_VALUE_COLUMN As Long = 2 '/ It would really help when naming to know what this data actually is that you need to copy.
    Const WORKBOOK_NAME_COLUMN As Long = 3

    testOutputData(CELL_VALUE_COLUMN, testOutputRowIndex) = "Cell Value"
    testOutputData(ADJACENT_CELL_VALUE_COLUMN, testOutputRowIndex) = "Cell Value in adjacent (to left) column"
    testOutputData(WORKBOOK_NAME_COLUMN, testOutputRowIndex) = "Workbook Name"

    '/================================================================================================================================================
    '/================================================================================================================================================

    Dim sheetData As Variant
    sheetData = Array()

    Dim i As Long, j As Long
    Dim cellValue As Variant, adjacentCellValue As Variant

    targetFilename = Dir(FOLDER_PATH & "*.xl??")

    Do While Len(targetFilename) > 0
        Set targetBook = Workbooks.Open(FOLDER_PATH & targetFilename, True, True)
        sheetCount = targetBook.Worksheets.Count

        For i = 1 To sheetCount
            Set targetSheet = targetBook.Sheets(i)

            Set sheetRange = targetSheet.Range("a1:b20") '/ include the adjacent column in our data
            sheetData = sheetRange

            For j = 1 To 20
                cellValue = sheetData(j, 2) '/ column "a" is in 1, so "b" is 2
                If cellValue <> "" And cellValue <> 0 And cellValue <> Null And cellValue Is Not Nothing And cellValue <> "Not Tested" Then '/ Check for other versions of [No Data]

                    adjacentCellValue = sheetData(j, 1)

                    testOutputRowIndex = testOutputRowIndex + 1
                    ReDim Preserve testOutputData(1 To 3, 1 To testOutputRowIndex) '/ add an extra row to the end

                    testOutputData(CELL_VALUE_COLUMN, testOutputRowIndex) = cellValue
                    testOutputData(ADJACENT_CELL_VALUE_COLUMN, testOutputRowIndex) = adjacentCellValue
                    testOutputData(WORKBOOK_NAME_COLUMN, testOutputRowIndex) = targetBook.Name

                End If
            Next j
        Next i

        targetBook.Close False
        targetFilename = Dir
    Loop

    '/ --> [Transpose data array back to (row, column) form]. You can find a function on the internet or write your own.

    '/ print final data array back to sheet
    Set sheetRange = outputSheet.Range(Cells(1, 1), Cells(testOutputRowIndex, 3))
    sheetRange = testOutputData

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic

End Sub