texts: Printing out all possible combination of printable ASCII 7-bit characters to stdout

texts:
This takes over 60 minutes to execute. The program is small in size, about 16kb. I am thinking that the repeated calls to printf slows it down significantly, rather than the nested for loops.

I used:

  gcc -Wall -o charsprint charsprint.c ./charsprint

Without removing the printf call: How could this source code be smaller and/or faster? Can the nested for loops be condensed using pointers?

#include<stdio.h>
#include<stdlib.h>

/*
* print out all combinations of chars between 1 and 5 chars
* 88 keys
* char combinations:
* basic a-f[26+] 0-9[10+] SPACE TAB CAPSLK ,./;'[]\-=`[14+]
* SHIFT A-F[26+] <>?:"{}|~!@#$%^&*()_+[21+]
* 52+35 = 87 chars available
* 87^5 = 4 984 209 207 possible combinations
*/

char ascii[] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,
        0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,
        0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,
        0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f,
        0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,
        0x28,0x29,0x2a,0x2b,0x2c,0x2d,0x2e,0x2f,
        0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,
        0x38,0x39,0x3a,0x3b,0x3c,0x3d,0x3e,0x3f,
        0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,
        0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,
        0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,
        0x58,0x59,0x5a,0x5b,0x5c,0x5d,0x5e,0x5f,
        0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,
        0x68,0x69,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f,
        0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,
        0x78,0x79,0x7a,0x7b,0x7c,0x7d,0x7e,0x7f
        };

int main(void){
    int i,j,x,y,z;
    i = j = x = y = z = 0x00;
    char result[] = {0x00,0x00,0x00,0x00,0x00,0x00};
    for (i=0x20; i<0x7e; i++){
        result[0] = ascii[i];
        for (j=0x20; j<0x7e; j++){
            result[1] = ascii[j];
            for (x=0x20; x<0x7e; x++){
                result[2] = ascii[x];
                for (y=0x20; y<0x7e; y++){
                    result[3] = ascii[y];
                    for (z=0x20; z<0x7e; z++){
                        result[4] = ascii[z];
                        printf("%s\n", result);
                    }
                }
            }
        }
    }
    printf("\nDone...\n");
    return 0;
}


texts:
This code is meant to retry the db operation when a DB connection breaks: OperationalError.

A transaction can fail for example when a db is being restarted and a commit fails. Or when a network error causes error in the DB transaction. (Variables-Names have been adjusted for demo).

My current method forcefully closes the current connection and re-establishes connections. Could there be a better way of doing this?

import psycopg2
from configs import mydb

class DBConnection:
    """connect to db to get data"""

    def __init__(self):
        self.establish_connections()

    def establish_connections(self):
        # connect to the database
        self.connection = psycopg2.connect(
            application_name="all_data",
            dbname=mydb.dbname,
            user=mydb.user,
            password=mydb.password,
            host=mydb.host,
        )
        self.connection.autocommit = True
        self.cursor = self.connection.cursor()
        print("Connected to DBConnection")

    def record_data(self, results):
        sql_command = f"""INSERT INTO
            msg_results(results)
            VALUES ('{results}');"""
        try:
            self.cursor.execute(sql_command)
        except psycopg2.OperationalError:
            print("psycopg2.OperationalError: record_data")
            # close old connection
            try:
                self.connection.close()
            except:
                print("Exception: in record_data while trying to close existing connection")
            #restart connection
            self.establish_connections()

            # TRY THE TRANSACTION AGAIN
            self.record_data(results)

        # another error occurred, this has failed, go home
        except Exception as e:
            print("CALCResultsConnection.record_data", str(e))
```


texts: Infix expression (with negative numbers) to postfix

texts:
I am writing a class to evaluate an arithmetic expression, For now my class can convert an infix expression into postfix, it doesn't support exponents yet.

    public class Evaluator {
        public Map<String, Operator> mOperators = new HashMap<>();

        public Evaluator() {
            addOperator(new Operator("+", 1) {
                @Override
                public BigDecimal eval(BigDecimal a, BigDecimal b) {
                    return a.add(b);
                }
            });

            addOperator(new Operator("-", 1) {
                @Override
                public BigDecimal eval(BigDecimal a, BigDecimal b) {
                    return a.subtract(b);
                }
            });

            addOperator(new Operator("*", 2) {
                @Override
                public BigDecimal eval(BigDecimal a, BigDecimal b) {
                    return a.multiply(b);
                }
            });

            addOperator(new Operator("/", 2) {
                @Override
                public BigDecimal eval(BigDecimal a, BigDecimal b) {
                    return a.divide(b);
                }
            });
        }

        public String toPostfix(String infix) {
            Stack<String> operators = new Stack<>();
            StringBuilder result = new StringBuilder();
            String[] tokens = infix.replaceAll("\\s+", "").split("(?<=[^.a-zA-Z\\d])|(?=[^.a-zA-Z\\d])");

            for (String token : tokens) {
                if (token.matches("-?\\d+(\\.\\d+)?")) {
                    result.append(token).append(" ");
                } else if (operators.isEmpty() || operators.peek().equals("(") || token.equals("(")) {
                    operators.push(token);
                } else if (token.equals(")")) {
                    while (!operators.peek().equals("(")) {
                        result.append(operators.pop()).append(" ");
                    }
                    operators.pop();
                } else {
                    while (!operators.isEmpty() && precedence(operators.peek()) >= precedence(token)) {
                        result.append(operators.pop()).append(" ");
                    }
                    operators.push(token);
                }
            }

            while (!operators.isEmpty()) {
                result.append(operators.pop()).append(" ");
            }

            return result.toString().trim();
        }

        public void addOperator(Operator operator) {
            mOperators.put(operator.getSymbol(), operator);
        }

        private int precedence(String token) {
            Operator operator = mOperators.getOrDefault(token, null);
            return operator == null ? -1 : operator.getPrecedence();
        }

        public abstract class Operator {
            private final String mSymbol;
            private final int mPrecedence;

            public Operator(String symbol, int precedence) {
                mSymbol = symbol;
                mPrecedence = precedence;
            }

            public abstract BigDecimal eval(BigDecimal a, BigDecimal b);

            public String getSymbol() {
                return mSymbol;
            }

            public int getPrecedence() {
                return mPrecedence;
            }
        }
}

My questions are:

How to deal with negative number, e.g: (-1) + 2
Is there any easier or better way to evaluate an arithmetic
expression without having to turn it into postfix?
What can I do to optimize my class and make it better?


texts: Compare two lists to see if one is a rotation of the other 2

texts:
Second attempt to solve this rotation problem, implemented a double ended queue as was suggested in a comment of my first attempt. So did I finally do the problem some justice or is there perhaps a better solution? Also anything I can and should clean up? I wanted to thank everyone from my previous post for their help and suggestions!

'''
Attempt 2
Problem statement: Given 2 integer arrays, determine if the 2nd array is a rotated version of the 1st array.
Ex. Original Array A={1,2,3,5,6,7,8} Rotated Array B={5,6,7,8,1,2,3}

@author: Anonymous3.1415
'''

from collections import deque

def is_rotated(lst1, lst2):
    '''is lst2 a rotation of lst1 '''

    if len(lst1) != len(lst2):
        return False
    if lst1 == [] and lst2 == []:
        return True

    d_lst1 = deque(lst1)
    d_lst2 = deque(lst2)

    #rotate all possible rotations to find match
    for n in range(len(d_lst1)):
        d_lst2.rotate(n)
        if d_lst2 == d_lst1:
            return True
        d_lst2.rotate(-n)
    return False

# rotation
lst1, lst2 = [1,2,3,4,6,4,7], [6,4,7,1,2,3,4]
assert is_rotated(lst1, lst2)

# rotation with repeated numbers
lst1, lst2 = [1,2,3,4,6,4,7,1], [6,4,7,1,1,2,3,4]
assert is_rotated(lst1, lst2)

# different set
lst1, lst2 = [1,2,3,4,6,4,6], [6,4,7,1,2,3,4]
assert not is_rotated(lst1, lst2)
lst1, lst2 = [1,2,3,4,6,4,7], [6,4,6,1,2,3,4]
assert not is_rotated(lst1, lst2)

# equal
lst2 = lst1
assert is_rotated(lst1, lst2)

# empty
lst1, lst2 = [], []
assert is_rotated(lst1, lst2)

# 1 empty, 1 not empty
lst1, lst2 = [], [1]
assert not is_rotated(lst1, lst2)
lst1, lst2 = [1], []
assert not is_rotated(lst1, lst2)


texts:
The next assignment in my class is to create a program that allows the user to input an inventory, and then display the total value of the inventory.  We are required to create a class with both private and public member functions.  I tried to keep it as streamlined as possible but I know there is always room for improvement.  Let me know what you think.

I defined the member functions outside of the class by direction of the prof. I personally like seeing it all in one place, but this is an OOP class, so I guess it makes sense to define them outside.  The only other direction was that all values have to be positive, hence the do while loops.

#include <iostream>

using namespace std;

class inventory
{
    private:
        int productNum[10];
        int productCount[10];
        double productPrice[10];

    public:
        int locator;
        void retrieve();
        void init();
        void store();

}inv1;

void setItemNumber(int &temp)
{
    do
    {
        cout << "\nPlease enter the item number (if finished please enter '0'): ";
        cout << "\nNumber must be positive: " << endl;
        cin >> temp;
    } while (temp < 0);
}
void setQuantity(int &temp)
{
    do
    {
        cout << "\nPlease enter the Quantity: ";
        cout << "\nNumber must be positive: " << endl;
        cin >> temp;
    } while (temp < 0);
}
void setPrice(double &price)
{
    do
    {
        cout << "\nPlease enter the Price: ";
        cout << "\nNumber must be positive: " << endl;
        cin >> price;
    } while (price < 0);
}

void inventory :: init()
{
    int counter = 0;
    while (counter < 10)
    {
        productCount[counter] = 0;
        productNum[counter] = 0;
        productPrice[counter]= 0;
        counter++;
        locator = counter;
    }
}

void inventory :: store()
{
    int counter = 0, temp = 0;
    double price = 0;
    cout << "\nWelcome to the inventory control system" << endl;
    cout << "When finished please enter '0' for the item number" << endl;
    while (counter < locator)
    {
        setItemNumber(temp);
        if(temp == 0)
        {
            locator = counter;
            return;
        }
        productNum[counter]=temp;
        setQuantity(temp);
        productCount[counter]=temp;
        setPrice(price);
        productPrice[counter]=price;
        counter++;
    }
}

void inventory :: retrieve()
{
    int counter = 0;
    double total = 0;
    cout << "Product Number \t\t Product Count \t\t Price" << endl;
    cout << "_______________________________________________________" << endl;
    while (counter < locator)
    {
        cout << productNum[counter];
        cout << "\t\t\t" << productCount[counter];
        cout << "\t\t\t" << productPrice[counter] << endl;
        total = productCount[counter] * productPrice[counter] + total;
        counter++;
    }
    cout << "Your total inventory is valued at: $" << total << endl;
}

int main()
{

    inv1.init();
    inv1.store();
    inv1.retrieve();

    return 0;
}


texts:
I've written the following explode function using break. The intended behavior is, that a list is divided into sublists by a predicate function, i.e. those elements which match the predicate are the separators - no empty lists should be returned.

Here are some examples:

explode id [True, True, False] = [[False]]
explode id [False, True, False] = [[False], [False]]
explode undefined [] = []
explode id [False, False, True, False] = [[False, False], [False]]
explode (\x -> mod x 3 == 0) [0..10] = [[1,2],[4,5],[7,8],[10]]

The signature of this function is:

explode :: (a -> Bool) -> [a] -> [[a]]

Here is the implementation:

explode _ [] = []
explode f xs
    | null zs = [z]
    | null z  = explode f (tail zs)
    | True    = z : explode f (tail zs)
        where (z, zs) = break f xs

Is there a better way to do this, a maybe more haskell-idiomatic one? Also, what is the complexity of such a function? I believe the running time is linear, but what about the space complexity?


texts: Calculate age given the birth date in the format YYYYMMDD

texts:
Here is method to calculate age given the birth date in the format YYYYMMDD.
function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}

Is it possible to make it more readable and easy to understand?
I don't want moment.js


texts: Interpolating code delimited with character that can appear in code

texts:
I've got a string that consists of an arbitrary combination of text and {} delimited python code, for instance, A plus b is {a + b}.  However, braces are used for dictionary and set literals in python, so You chose the {{1:"first", 2:"second"}[choice]} option should also be interpretted correctly.  It's also valid to have more than one python expression in the input, so You picked {choice1} and {choice2} is valid.

Here's my current code:

protected String ParseStringForVariable([NotNull] String str)
{
    PythonEngine.PythonEngine pythonEngine = GetCurrentCore().PythonEngine;

    for (int i = 0; i < str.Length; i++)
    {
        if (str[i] != '{')
        {
            continue;
        }

        int opening = i;
        foreach (var expression in from closing in str.IndexesWhere('}'.Equals)
                                   where closing > opening
                                   select new
                                          {
                                              Template = str.Substring(opening, closing - opening + 1),
                                              Code = str.Substring(opening + 1, closing - opening - 1)
                                          })
        {
            PythonByteCode compiled;
            try
            {
                compiled = pythonEngine.Compile(expression.Code, PythonByteCode.SourceCodeType.Expression);
            }
            catch (PythonParseException)
            {
                // not valid python, try next expression
                continue;
            }
            String result = pythonEngine.Evaluate(compiled).ToString();
            str = str.Replace(expression.Template, result);
            break;
        }
    }

    return str;
}

It works by looking at progressively longer strings, attempting to parse them, and ignoring them if it's not valid python.  This is done with the PythonEngine class, which is a wrapper around the IronPython interpretter, and has an extensive test suite, so can assumed to be correct.

It appears to burp slightly if the value of the first of multiple python expression contains an opening brace: {"{"} {"}"}, what's the best way to prevent that?
Resharper is complaining about access to modified closures, can you provide a test case that exposes why that is an issue?
It works under all inputs I've tested it with, but what edge cases should be included in the test suite? (It's intended behaviour that invalid python code is left as-is).  Current thoughts include:

Empty string
without braces
empty braces
valid python in braces
invalid python
both valid and invalid
both valid and empty
both invalid and empty
valid, nested braces
invalid, nested braces
valid, evaluated to contain open brace
valid, evaluated to contain close brace - irrelevant, as parsing is LTR?
valid, evaluated to contain open brace followed by further invalid
valid, evaluated to contain open brace followed by further empty
unmatched open brace
unmatched close brace

Are there any improvements that jump out?  Clarity, performance, style?


texts: "String Enum" implementation - comments?

texts:
I have a need to represent a finite set of discrete string values:

When these strings are used in code, they must belong to the valid set, or serious errors (or worse) can occur.
As "magic strings" are a terrible code smell, I want to encapsulate the strings within a non-string type, so that I can require the use of my type instead of just a string and thus enforce at compile-time that a value is given that I know will work.
No constants; if I change the string behind the scenes I should not have to recompile all usages of my type.
The identifiers representing the valid values should not have to have any formulaic similarity to the actual string (no Enum.ToString or similar).
Lastly, while I want to enforce the use of my type so I can restrict values to the ones I know are valid, the type must be easily convertible to a string so that the piece of code that really needs the string doesn't have to undergo a complicated or esoteric conversion.

What I came up with is a variation of a "multiton"; a class that cannot be instantiated in code, but has a finite number of static instances each representing a valid value of the type. They are implicitly convertible to strings and so the static members just drop in wherever a string is needed.

//abstract base; derive to create your specific set of values
public abstract class StringEnum
{
    protected StringEnum(string name)
    {
        this.name = name;
    }

    private readonly string name;

    public static implicit operator string(StringEnum sp)
    {
        return sp.name;
    }
}

//one possible derivation
public class CommandNames:StringEnum
{
    //unfortunately each derivation has to call back to the base constructor;
    //it would be nice not to have to do this, but meh
    protected CommandNames(string commName) : base(commName) { }

    //obviously the instance names don't have to match the real string value exactly
    public static readonly CommandNames DoSomething = new CommandNames("system638_Command_doSomething");
}

//example usage
public void ExecuteCommand(CommandNames name)
{
    //assume ExecuteByName expects a string
    CommandExecutor.ExecuteByName(name); //the StringEnum just drops in
}

...

//Only one of the static instances, with string values I control,
//can be passed into this function, thus safely encapsulating the inner
//objects' use of "magic strings".
ExecuteCommand(CommandNames.DoSomething);

Thoughts?


texts:
In my continued venture to teach myself C# I came across an exercise using Dictionary.  I created a class that has a method.  In that method it creates a dictionary with keys/values.  A string is passed into that method.  If any matching character in that string correlates with a key we increment the value of that key, else we throw an ArgumentException.  This is my code an my first real attempt and working with a dictionary in C#.

I am interested to see if there is a better, concise, an/or faster way to do the same task.  Following is my code and following that is the test.  Test can not be altered.  I tried turning foreach into linq without luck so that would be interesting to see that as well if you know how or recommend it.

For more information My Github link to this exercise.

using System;
using System.Collections.Generic;

public static class NucleotideCount
{
    public static IDictionary<char, int> Count(string sequence)
    {
        Dictionary<char, int> Dna = new Dictionary<char, int>()
        {
            {'A', 0},
            {'C', 0},
            {'G', 0},
            {'T', 0}
        };

        foreach (char c in sequence)
        {
            switch (c)
            {
                case 'A': Dna[c]++; break;
                case 'C': Dna[c]++; break;
                case 'G': Dna[c]++; break;
                case 'T': Dna[c]++; break;
                default : throw new ArgumentException("Strand has invalid nucleotides.");
            }
        }

        return Dna;
    }
}

// This file was auto-generated based on version 1.3.0 of the canonical data.

using System;
using System.Collections.Generic;
using Xunit;

public class NucleotideCountTests
{
    [Fact]
    public void Empty_strand()
    {
        var expected = new Dictionary<char, int>
        {
            ['A'] = 0,
            ['C'] = 0,
            ['G'] = 0,
            ['T'] = 0
        };
        Assert.Equal(expected, NucleotideCount.Count(""));
    }

    [Fact]
    public void Can_count_one_nucleotide_in_single_character_input()
    {
        var expected = new Dictionary<char, int>
        {
            ['A'] = 0,
            ['C'] = 0,
            ['G'] = 1,
            ['T'] = 0
        };
        Assert.Equal(expected, NucleotideCount.Count("G"));
    }

    [Fact]
    public void Strand_with_repeated_nucleotide()
    {
        var expected = new Dictionary<char, int>
        {
            ['A'] = 0,
            ['C'] = 0,
            ['G'] = 7,
            ['T'] = 0
        };
        Assert.Equal(expected, NucleotideCount.Count("GGGGGGG"));
    }

    [Fact]
    public void Strand_with_multiple_nucleotides()
    {
        var expected = new Dictionary<char, int>
        {
            ['A'] = 20,
            ['C'] = 12,
            ['G'] = 17,
            ['T'] = 21
        };
        Assert.Equal(expected, NucleotideCount.Count("AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC"));
    }

    [Fact]
    public void Strand_with_invalid_nucleotides()
    {
        Assert.Throws<ArgumentException>(() => NucleotideCount.Count("AGXXACT"));
    }
}


texts: Python generator function that yields combinations of elements in a sequence sorted by subset order

texts:
In Python, itertools.combinations yields combinations of elements in a sequence sorted by lexicographical order.  In the course of solving certain math problems, I found it useful to write a function, combinations_by_subset, that yields these combinations sorted by subset order (for lack of a better name).

For example, to list all 3-length combinations of the string 'abcde':

>>> [''.join(c) for c in itertools.combinations('abcde', 3)]
['abc', 'abd', 'abe', 'acd', 'ace', 'ade', 'bcd', 'bce', 'bde', 'cde']

>>> [''.join(c) for c in combinations_by_subset('abcde', 3)]
['abc', 'abd', 'acd', 'bcd', 'abe', 'ace', 'bce', 'ade', 'bde', 'cde']

Formally, for a sequence of length \$n\$, we have \$\binom{n}{r}\$ combinations of length \$r\$, where \$\binom{n}{r} = \frac{n!}{r! (n - r)!}\$

The function combinations_by_subset yields combinations in such an order that the first \$\binom{k}{r}\$ of them are the r-length combinations of the first k elements of the sequence.

In our example above, the first \$\binom{3}{3} = 1\$ combination is the 3-length combination of 'abc' (which is just 'abc'); the first \$\binom{4}{3} = 4\$ combinations are the 3-length combinations of 'abcd' (which are 'abc', 'abd', 'acd', 'bcd'); etc.

My first implementation is a simple generator function:

def combinations_by_subset(seq, r):
    if r:
        for i in xrange(r - 1, len(seq)):
            for cl in (list(c) for c in combinations_by_subset(seq[:i], r - 1)):
                cl.append(seq[i])
                yield tuple(cl)
    else:
        yield tuple()

For fun, I decided to write a second implementation as a generator expression and came up with the following:

def combinations_by_subset(seq, r):
    return (tuple(itertools.chain(c, (seq[i], ))) for i in xrange(r - 1, len(seq)) for c in combinations_by_subset(seq[:i], r - 1)) if r else (() for i in xrange(1))

My questions are:

Which function definition is preferable? (I prefer the generator function over the generator expression because of legibility.)
Are there any improvements one could make to the above algorithm/implementation?
Can you suggest a better name for this function?


texts: Printing chessboard with *(asterisk) and .(dot)

texts:
I have written a program in which user enters total number of conditions (cases) and then that many number of inputs to print chessboard.

For example:

3
21
*
.
12
*.
35
*.*.*
.*.*.
*.*.*

Here is my code:

def main():
    no_of_case = input()
    for i in range(no_of_case):
        user_input = input()                    # take input

        row = int(str(user_input)[0])
        column = int(str(user_input)[1])

        count = 0

        a = "*"
        b = "."

        while True:
            count = count +1

            if row == 1 and column == 1:
                print "*."
                break

            if row == 1 and column%2 == 0:
                print (a + b) * (column/2)
                break

            if row == 1 and column%2 != 0:
                print (a + b) * (column/2) + "*"
                break

            if column == 1 and row%2 == 0:
                print a
                print b
                if count == row/2:
                    break

            if column == 1 and row%2 != 0:
                print a
                print b

                if count == row/2:
                    print "*"
                    break

            if row != 1 and column !=1:

                if (row%2 == 0) and (column%2== 0):
                    print (a + b) * (column/2)
                    print (b + a) * (column/2)

                elif (row%2 != 0) and (column%2 == 0):
                    print (a + b) * (column/2)
                    print (b + a) * (column/2)

                elif (row%2 == 0) and (column%2 != 0):
                    print (a + b) * (column/2) + "*"
                    print (b + a) * (column/2) + "."

                elif (row%2 != 0) and (column%2 != 0):
                    print (a + b) * (column/2) + "*"
                    print (b + a) * (column/2) + "."

                if row%2 == 0 and count == row/2:
                    break

                elif row%2 != 0 and count == row/2:
                    if column%2 == 0:
                        print "*." * (column/2)
                    elif column%2 != 0:
                        print "*." * (column/2) + "*"
                    break

main()

Any suggestion in what way I can improve it?


texts:
I've implemented the sliding blocks puzzle in Python to solve it using different algorithms.
I'd like to know if the class "Sliding_blocks" is nicely designed or if I am missing
concepts of OOP.

I think that the indices of the blocks are a bit obfuscated, because I mix tuples,
lists and arrays (arrays are better to add but then I have to convert them to tuples
at some point).

I use the A* algorithm with the number of misplaced blocks as heuristic function.
It's quite slow and I think's it's because I have to create many copies of objects.

I'm more concerned with best practices than speed.

The code is:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import numpy as np
from copy import copy, deepcopy

class Sliding_blocks():

    def __init__(self):
        self.size = 4
        self.block = self.generate_block()

    def generate_block(self):
        """Goal state"""

        block = np.arange(1,self.size**2)
        block.resize(self.size,self.size)
        return block

    def move(self, piece):
        """Moves the piece with index "piece" to free place, if possible"""

        if list(piece) in self.find_moves():
            self.block[tuple( self.find_free() )] = self.block[tuple(piece)]
            self.block[tuple(piece)] = 0
            return "success"
        else:
            return "error"

    def find_free(self):
        """Returns array of indices of the free cell"""

        free_position = np.where(self.block == 0)
        free_position = np.array(free_position).flatten()
        return free_position

    def find_moves(self):
        """Returns list of allowed indices to move"""

        from itertools import product
        free_position = self.find_free()
        return [list(free_position+i) for i in [[0,1],[1,0],[-1,0],[0,-1]] if tuple(i+free_position) in product(range(self.size),repeat=2)]

    def shuffle(self):
        steps = 30
        for i in xrange(steps):
            self.rand_move()

    def rand_move(self):
        from random import choice

        self.move(choice(self.find_moves()))

    #The following functions are used to find the solution

    def isWin(self):
        return (self.block == self.generate_block()).all()

    def total_misplaced(self):
        return np.sum( self.block != self.generate_block() )

def tree_search():#
    Game = Sliding_blocks()
    Game.shuffle()

    frontier = [[Game]]
    explored = []

    while 1:
        if frontier==[]: return "Error"

        path, frontier = remove_choice(frontier)
        endnode = path[-1]
        explored.append(endnode)
        if endnode.isWin(): return path

        #Iterate over all possible actions at endnode
        for action in allactions(endnode):
            if not action in explored and not action in frontier or action.isWin():
                pathtem=copy(path)
                pathtem.append(action)
                frontier.append(pathtem)

def allactions(obj):
    possible = obj.find_moves()
    actions = []
    for i in range(len(possible)):
        actions.append(deepcopy(obj))
        actions[i].move(possible[i])
    return actions

#A*
def a_star(frontier):
    #Calculates the cost (lenght + number misplaced cells)
    #of all paths in frontier, returns the frontier
    #without the least expensive path and also returns that path

    lengths = [f[-1].total_misplaced()+cost(f) for f in frontier]
    shortest=[i for i,l in enumerate(lengths) if l<=min(lengths)]
    return frontier.pop(shortest[0]), frontier

def cost(path): return len(path)

if __name__ == "__main__":

    remove_choice = a_star
    sol = tree_search()
    for s in sol:
        print s.block
        print "\n"


texts:
My JavaScript code is slow for large inputs. However, it is especially slow in IE. The browser will freeze for about a minute while the select is being reloaded. Any ideas for how to optimize this code, especially for IE?

function reloadSelectWithJSON (elementid,query){
        /* It is assumed that the elementid passed in is
  the selected box's ID while 'available_' added to it is the available box's ID */
    var preElement = 'available_' + elementid;
    var element = document.getElementById(preElement);
    var selected = document.getElementById(elementid);

    /* Gathers a string consisting of all the selected values */
    var selectedList = '';
    for (var h = 0; h < selected.length; h++){
        selectedList = selectedList + ',' + selected.options[h].value;
    }

    selectedList = selectedList.substr(1).toLowerCase();

    //Clear select of exiting options
    element.options.length = 0;

    //Creates a blank option if the optional arguments {id,name} are passed
    if (this.reloadSelectWithJSON.arguments.length == 4) {
        var id = this.reloadSelectWithJSON.arguments[2];
        var name = this.reloadSelectWithJSON.arguments[3];
        element.options[0] = new Option(name,id);
    }

    //Loop JSON query structure and reload select
    for (var i=0; i < query.ROWCOUNT; i++){
   /* If the value is part of the selected values list then do not include it as an available column */
        if(selectedList.search(query.DATA.ID[i].toString().toLowerCase()) == -1){
            element.options[element.options.length] = new Option(query.DATA.NAME[i], query.DATA.ID[i]);

            var optionLength = element.options.length;

            optionLength--;

            if(query.DATA.title != undefined  && element.options[optionLength] != undefined){
            element.options[optionLength].setAttribute("title",query.DATA.title[i]);
            } else {
            element.options[optionLength].setAttribute('title',query.DATA.NAME[i]);
            }
        }
    }
}


texts: Refer to other cells besides the one in the Cells.Find

texts:
I have the following that loops through a range.  When the initial value is found on the second sheet it goes to the cell to be able to compare some date values on the same row.  Once the comparison is complete another value from the same row is copied to be placed back onto the first sheet.  I believe the Application.Goto which activiates the second sheet and the other Sheets("Data").Activate is really slowing this down.  It loops through about 26k rows and takes about 12 minutes.  I don't know of another way to refer to the other cells in the second sheet in regards to the found value in both sheets without activating sheets back and forth.

Sub oiyuou()

Dim rFound As Range
Dim dtStartTime As Date
dtStartTime = Now()

Application.ScreenUpdating = False
Range("A2").Select

Do Until ActiveCell.Offset(0, 4).Value = ""

    Application.StatusBar = ActiveCell.Row
    sdate = ActiveCell.Offset(0, 6).Value
    sCat = ActiveCell.Offset(0, 1).Value & ActiveCell.Offset(0, 3).Value 'concat of two cells

    'find in other worksheet
    Set rFound = Sheets("User").Cells.Find(What:=sCat, _
                                            After:=ActiveCell, _
                                            LookIn:=xlValues, _
                                            LookAt:=xlPart, _
                                            SearchOrder:=xlByRows, _
                                            SearchDirection:=xlNext, _
                                            MatchCase:=False, _
                                            SearchFormat:=False)

    If rFound Is Nothing Then
        sdept = ""
    Else: Application.Goto rFound, True 'i assume this is the way to go so i can compare my sdate with these other values
        If (sdate >= ActiveCell.Offset(0, 3).Value And sdate <= ActiveCell.Offset(0, 4).Value) Or ActiveCell.Offset(0, 4).Value = "" Then
            sdept = ActiveCell.Offset(0, 2).Value
        Else: sdept = ""
        End If
    End If

    Sheets("Data").Activate  'back to first sheet to populate with found value sdept
    ActiveCell.Value = sdept
    ActiveCell.Offset(1, 0).Select

Loop

Application.ScreenUpdating = True
MsgBox "Macro ran successfully in " & _
            FormatDateTime(Now() - dtStartTime, 3), vbInformation
End Sub

EDIT
I was able to get around the back and forth of updating sheets but it still takes the same amount of time.  So this narrows it down to the loop itself.
This is what I replaced in case it helps anyone.  I found it extremly helpful that you could call the rFound.address.  Once I knew I could call that then I could use the offset to refer to the other values.

Set rFound = Sheets("User").Cells.Find(What:=sCat, _
                                            After:=ActiveCell, _
                                            LookIn:=xlValues, _
                                            LookAt:=xlPart, _
                                            SearchOrder:=xlByRows, _
                                            SearchDirection:=xlNext, _
                                            MatchCase:=False, _
                                            SearchFormat:=False)

    sEff = rFound.Offset(0, 3).Value
    sTerm = rFound.Offset(0, 4).Value

    If rFound Is Nothing Then
        sdept = ""
    End If

    If (sdate >= sEff And sdate <= sTerm) Or sTerm = "" Then
        sdept = rFound.Offset(0, 2).Value
    Else: sdept = ""
    End If

   ' Sheets("Data").Activate
    ActiveCell.Value = sdept
    ActiveCell.Offset(1, 0).Select


texts: How Long Will Your Smartphone Distract You From Family Dinner?

texts:
I wrote a program to simulate this week's 538 Riddler, reproduced below:

  You’ve just finished unwrapping your holiday presents. You and your
  sister got brand-new smartphones, opening them at the same moment. You
  immediately both start doing important tasks on the Internet, and each
  task you do takes one to five minutes. (All tasks take exactly one,
  two, three, four or five minutes, with an equal probability of each).

  After each task, you have a brief moment of clarity. During these, you
  remember that you and your sister are supposed to join the rest of the
  family for dinner and that you promised each other you’d arrive
  together. You ask if your sister is ready to eat, but if she is still
  in the middle of a task, she asks for time to finish it. In that case,
  you now have time to kill, so you start a new task (again, it will
  take one, two, three, four or five minutes, exactly, with an equal
  probability of each). If she asks you if it’s time for dinner while
  you’re still busy, you ask for time to finish up and she starts a new
  task and so on.

  From the moment you first open your gifts, how long on
  average does it take for both of you to be between tasks at the same
  time so you can finally eat? (You can assume the “moments of clarity”
  are so brief as to take no measurable time at all.)

And the program itself:

private static int numberOfSimulations = 100000;
static void Main(string[] args)
{
    var rand = new Random();
    var simulationTimes = new List<int>();
    for (int i = 0; i < numberOfSimulations; i++)
    {
        var totalTime = 0;
        var myTaskTime = rand.Next(1, 6);
        var herTaskTime = rand.Next(1, 6);

        do
        {
            if (herTaskTime > myTaskTime)
            {
                totalTime += myTaskTime;
                herTaskTime -= myTaskTime;
                myTaskTime = rand.Next(1, 6);
            }
            else if (herTaskTime < myTaskTime)
            {
                totalTime += herTaskTime;
                myTaskTime -= herTaskTime;
                herTaskTime = rand.Next(1, 6);
            }
            else
            {
                totalTime += myTaskTime;
            }
        } while (myTaskTime - herTaskTime != 0);

        simulationTimes.Add(totalTime);
    }
    Console.WriteLine(simulationTimes.Average());
    Console.ReadLine();
}

Anecdotally, I'm consistently getting ~7.5 minutes.

I'm just looking for a general code review - does this look correct? Am I doing anything dumb? Should I have done it differently?


texts:
I'm learning Clojure and I'm interested in areas that could be more idiomatic. The main function is below. If you're interested in the whole lib, check out this.

The function operates on a grid, which contains a finite number of cells. A cell is a single point in a grid. neighbours-of will get information about moving one step away from a given cell. The info is in the form of a set of neighbouring cells, and a map giving the cost of moving to a given neighbour.

The loop vars are open-nodes, which is a sorted list of cell/cost pairs, visited-cells, which is a set of cells we don't want to look at again, and parents, which is a map giving the parent of a given cell.

parents is used in create-route to produce a path as a list of cells.

It doesn't currently handle the no-route case, nor is it very optimal. I'm not worried about the first, but if you have hints on the latter then that would be great (that order-by is probably a hotspot for large grids). Mostly I'm interested in what is and is not idiomatic.

(defn navigate-to [grid start dest]
  "provides route from start to dest, not including start"
  (validate-cell grid start)
  (validate-cell grid dest)
  (loop [[{current-cell :cell current-cost :cost} & open-nodes] (list (traversal 0 start))
         visited-cells #{}
         parents {}]
    (if (= dest current-cell)
      (create-route parents current-cell)
      (let [;; traversals is list of {:cell :cost}
            {all-neighbours :neighbours traversals :traversals} (neighbours-of
                                                                 grid
                                                                 current-cell)
            unvisited-neighbours (set/difference all-neighbours visited-cells)
            ;; add current route cost to traversals:
            neighbour-total-distances (into {}
                                            (for [[neighbour cost] traversals]
                                              [neighbour (+ current-cost cost)]))
            ;; keep bigger distances
            ;; ...first merge in seen neighbours, keeping higher values
            better-neighbours (->> open-nodes
                                   (filter
                                    (fn [{open-cell :cell current-cost :cost :as open-node}]
                                      (and (contains? unvisited-neighbours open-cell)
                                           (> current-cost
                                              (neighbour-total-distances open-cell)))))
                                   (map #(% :cell))
                                   set)
            updated-open (map (fn [{open-cell :cell current-cost :cost :as open-node}]
                               (if (contains? better-neighbours open-cell)
                                 (traversal (neighbour-total-distances open-cell) open-cell)
                                 open-node))
                              open-nodes)
            updated-parents (reduce #(assoc %1 %2 current-cell) {} better-neighbours)
            ;; ...then create new neighbours
            all-open-cells (set (map #(% :cell) open-nodes))
            new-neighbours (set/difference unvisited-neighbours all-open-cells)
            new-open-nodes (map #(traversal (neighbour-total-distances %) %) new-neighbours)
            new-parents (reduce #(assoc %1 %2 current-cell) {} new-neighbours)]
        (recur (sort-by :cost (concat updated-open new-open-nodes))
               (conj visited-cells current-cell)
               (merge parents updated-parents new-parents))))))


texts: Generate power sets given a set of elements in java

texts:
For an array of length n, the possible number of subsets is Math.pow(2, n).  for each value between 0 and Math.pow(2, n), see the index at which the bit is set, and include the corresponding number in the given input to the current subset.

public List<List<Integer>> subsets(int[] nums){
        int numOfSubSets = 1 << nums.length;
        List<List<Integer>> subsets = new ArrayList<>();
        int index = -1;
        subsets.add(new ArrayList<>());
        List<Integer> tempSubset;
        int current = 0;
        for(int i = 1 ; i < numOfSubSets ; i++ ){
            index = -1;
            tempSubset = new ArrayList<>();
            current = i;
            while(current != 0){
                index++;
                if((current & 1) != 0){
                    tempSubset.add(nums[index]);
                }
                current = current >> 1;
            }
            subsets.add(tempSubset);
        }
        return subsets;
    }


texts: Cleaning up conditional statements regarding new values

texts:
Please suggest ways of cleaning up this code.

Hashtable newValues = e.Values;

string NewPosition = null;
string NewFirst = null;
string NewLast = null;
string NewEmail = null;
int NewAppt = 0;

if (newValues["Position"] == null)
{
    NewPosition = "";
}
else
{
    NewPosition = newValues["Position"].ToString();
}

if (newValues["First Name"] == null)
{
    NewFirst = "";
}
else
{
    NewFirst = newValues["First Name"].ToString();
}

if (newValues["Last Name"] == null)
{
    NewLast = "";
}
else
{
    NewLast = newValues["Last Name"].ToString();
}

if (newValues["Email"] == null)
{
    NewEmail = "";
}
else
{
    NewEmail = newValues["Email"].ToString();
}

if (newValues["Appts"] == null)
{
    NewAppt = 0;
}
else
{
    NewAppt = 1;
}


texts: Exception-safety: add cleaning up actions during the execution

texts:
I need to call some functions and clean up some resources acquired after those calls. I can't just call some determined Cleanup function in the end, because during the execution of the functions exceptions may be thrown, so the precise cleanup action depends on the point at which exception is thrown (it may be thrown in the first function, in second, ...). So I created Cleaner helper class, in which I register cleaning actions, specific for each function. If at some point exception is thrown, only cleanup actions that are really needed (and are correct) will be called.

#include <functional>
#include <vector>

using CleanupAction = std::function<void()>;

class Cleaner
{
public:
    void AddCleanupAction(const CleanupAction &i_action)
    {
        m_cleanup_actions.push_back(i_action);
    }
    ~Cleaner()
    {
        for (auto &action : m_cleanup_actions)
            action();
    }
private:
    std::vector<CleanupAction> m_cleanup_actions;
};

struct SomethingFirstDoer
{
    static void Do()
    {
        // do something first ...
    }

    static CleanupAction GetCleanupAction()
    {
        return []()
        {
            // cleanup needed for the first action..
        };
    }
};

struct SomethingSecondDoer
{
    static void Do()
    {
        // do something second ...
    }

    static CleanupAction GetCleanupAction()
    {
        return []()
        {
            // cleanup needed for the second action..
        };
    }
};

void DoSomething(Cleaner &i_cleaner)
{
    SomethingFirstDoer::Do();
    i_cleaner.AddCleanupAction(SomethingFirstDoer::GetCleanupAction());

    SomethingSecondDoer::Do();
    i_cleaner.AddCleanupAction(SomethingSecondDoer::GetCleanupAction());
}

void DoSomethingWithCleanup()
{
    Cleaner cleaner;
    DoSomething(cleaner);
}

Any remarks, low-level and high-level, would be appreciated.

UPDATE 1:

Another version of the code: now it doesn't use the Cleaner class, just relay on local objects destructors.

#include <functional>

#include <boost/scope_exit.hpp>

using CleanupAction = std::function<void()>;

struct SomethingFirstDoer
{
    static void Do()
    {
        // do something first ...
    }

    static CleanupAction GetCleanupAction()
    {
        return []()
        {
            // cleanup needed for the first action..
        };
    }
};

struct SomethingSecondDoer
{
    static void Do()
    {
        // do something second ...
    }

    static CleanupAction GetCleanupAction()
    {
        return []()
        {
            // cleanup needed for the second action..
        };
    }
};

void DoSomething()
{
    SomethingFirstDoer::Do();
    BOOST_SCOPE_EXIT(void) {
        SomethingFirstDoer::GetCleanupAction();
    } BOOST_SCOPE_EXIT_END

    SomethingSecondDoer::Do();
    BOOST_SCOPE_EXIT(void) {
        SomethingSecondDoer::GetCleanupAction();
    } BOOST_SCOPE_EXIT_END
}


texts: Document (PDF, TXT, DOCX) to text classes

texts:
I wrote some classes to convert some documents (PDF, DOC, DOCX and TXT) to only text so that it can be stored in a search engine.

Here's how I use those classes :

$file = 'text.doc'; // comes from the user, hardcoded for the example
$file_extension = pathinfo($file, PATHINFO_EXTENSION);

switch($file_extension){
    case 'pdf':
        $reader = new PDFConverter($file);
        break;
    case 'text':
        $reader = new TXTConverter($file);
        break;
    case 'doc':
        $reader = new DOCConverter($file);
        break;
    case 'docx':
        $reader = new DOCXConverter($file);
        break;
}

$reader->handle();
$text = $reader->getText();

Here's the parent Converter class :

class Converter
{
    protected $file;
    protected $text;

    public function __construct($file)
    {
        $this->file = $file;
    }

    public function getText()
    {
        return $this->text;
    }
}

Here's one of the converter class, PDFConverter :

class PDFConverter extends Converter implements IConverter
{
    public function handle()
    {
        $this->text = 'Text PDF'; // just for demo
    }
}

And finally the IConverter interfaces that all subclasses implement :

interface IConverter
{
    public function handle();
}

How does this look? Is this a good use of inheritance/interfaces? Any pointers on how to structure this better would be appreciated.

I've removed the logic from the subclasses' handle() method to keep things simple for Codereview.


texts: Raising an error for slug unique in django

texts:
I have the following model in models.py:

class Question(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, db_index=True, unique=True)

for which i use a generic view:

class QuestionCreate(generic.CreateView):
    model = Question
    fields = ['title', 'text']
    def form_valid(self, form):
        instance = form.save(commit=False)
        slug = slugify(form.cleaned_data['title'])
        if Question.objects.filter(slug=slug).exists():
             form.add_error("title","This Question already exist")
             return self.form_invalid(form)

The idea is to automatically create a slug from the users title to use for url, is this approach okay if i want to do this? Is the way i added the error message correct?


texts: Parse.com simple query: login and display account balance

texts:
I was recently at a hackathon and saw quite a few people using Parse, so I decided to check it out and read some guides online. Can someone take a look at my code? I followed Parse documentation so it should be fairly readable. I'm trying to get the balance for the user when they log in and display it.

Parse.User.logIn("user", "pass", {
  success: function(user) {
    query.find({
      success: function(results) {
        results[0].save({ key: value }, {
          success: function(result) {

            var arr = result.balances;
            var balance = sumArray(arr);
            var charge = result.charge;

            if(balance < charge)
                document.write("Insufficient funds. Must have " + balance + charge + " balance left");
            else if(balance == charge)
                document.write("Oops!");
                document.write("Sorry, balance cannot reach zero");

            var mssg = "";
            var today = formatDate(new Date());

            for(var i=0; i<arr.length; i++) {
                mssg += arr[i] + " ,";
            }
            document.write(today - 1 + 1);
            document.write(mssg);

          },
          error: function(result, error) {
            console.log(error);
          }
        });
      },
      error: function(error) {
        console.log(error);
      }
    });
  },
  error: function(user, error) {
    console.log(error);
  }
});

function sumArray(arr) {
    var S = 0;
    for(var i=0; i<arr.length; i++){
        S += arr[i];
    }
    return S;
}

$(document).ready(function () {
    $("#dialog-confirm").dialog({
        autoOpen: false,
        height: 'auto',
        width: '400px',
        modal: true,
        buttons: {
            Cancel: function () {
                $(this).dialog("close");
            }
        }
    });

    $(function () {
        $("#form").datepicker({
            maxDate: '-18y'
        });
        $("#form").mask("99/99/9999", { placeholder: "mm/dd/yyyy" });
    })
});

function formatDate(date) {
    var d = new Date(date);
    var day = '' + d.getDate();

    return day;
}


texts:
I have a Slack bot that takes a stream of messages and the idea is that if 3 different users repeat the same message, the bot will also mime that message.

I am just beginning with RXJS and I am trying to figure out the correct, most idiomatic way to refactor the following code.  Is it even possible with what I'm trying to do here?

JSBin

let repeat = {
    count: 0,
    message: '',
    users: []
};

const reset = () => {
    repeat.count = 0;
    repeat.message = '';
    repeat.users.length = 0;
};

module.exports = (source) => {
    source
        .filter(message => {
            // Sets initial message if there is no prior message
            if (!repeat.message) {
                repeat.message = message.text;
                repeat.users.push(message.user);

                return true;
            }

            // The message is the same and it's not repeated by a known user
            if (repeat.message === message.text && !!~repeat.users.indexOf(message.user)) {
                repeat.users.push(message.user);

                return true;
            }

            // Starts a new sequence
            reset();
            repeat.users.push(message.user);
            repeat.message = message.text;

            return false;
        })
        .subscribe(message => {
            repeat.count++;

            if (repeat.count === 3) {
                console.log(message.text);
                reset();
            }
        });
}


texts: Calculate class to practice encapsulation

texts:
I realize this is very beginner code, but I just today grasped the basic concepts of private variables, constructors, and such. I wrote this very simple class, and a class to test it. Any and all input welcome.

Calculate.java

import java.lang.Math.*;

public class Calculate {
    private final double num1, num2;

    Calculate(double num1, double num2) {
        this.num1 = num1;
        this.num2 = num2;
    }

    public double Add() {
        return num1 + num2;
    }
    public double Subtract() {
        return num1 - num2;
    }
    public double Multiply() {
        return num1 * num2;
    }
    public double Divide() {
        return num1 / num2;
    }
    public double Exponent() {
        return Math.pow(num1, num2);
    }
}

TestCalculate.java

class TestCalculate {
    public static void main(String[] args) {
        double num1 = 5, num2 =7;
        Calculate calc = new Calculate(num1, num2);
        // show outputs from calculations
        System.out.println("Number 1: " + num1);
        System.out.println("Number 2: " + num2);
        System.out.println("Addition: " + calc.Add());
        System.out.println("Subtraction: " + calc.Subtract());
        System.out.println("Multiplication: " + calc.Multiply());
        System.out.println("Division: " + calc.Divide());
        System.out.println("Exponent: " + calc.Exponent());
    }
}

Sample output using given variables:

  Success   time: 0.1 memory: 320256 signal:0 Number 1: 5.0 Number
  2: 7.0 Addition: 12.0 Subtraction: -2.0 Multiplication:
  35.0 Division: 0.7142857142857143 Exponent: 78125.0


texts:
I am trying to optimize the following switch statement, but I'm having a brain fart about how to do it. Here's the code:

$('.newsroom-tabs div.pane-content ul li').click(function(){
// get the class name of the clicked link
var className = $(this).attr('class');
// variable so that jQuery isn't traversing the DOM each time
var hideFeaturedArticle = $('.featured-article').hide();
// based on the category selected, the featured article will
// show for that section
switch(className) {
    case 'air-quality-news-tab':
        hideFeaturedArticle;
        $('.featured-article.aqn').fadeIn(300);
        break;
    case 'awards-and-reviews-tab':
        hideFeaturedArticle;
        $('.featured-article.aar').fadeIn(300);
        break;
    case 'in-the-community-tab':
        hideFeaturedArticle;
        $('.featured-article.itc').fadeIn(300);
        break;
    case 'press-releases-tab':
        hideFeaturedArticle;
        $('.featured-article.pr').fadeIn(300);
        break;
    default:
        return className;

}
});

I feel like hiding the tabs each time is inefficient, but I'm not sure how to do this otherwise. Is there anything else I could do better here?


texts:
I'm trying to do some datetime processing. The input is a string of the form 20141005 ('%Y%m%d') and I want to return a data structure that stores the day before the input date, the day from the input, and the day after along with the day after that in a %y%m%d format (141005)

This is my function right now, and I'm wondering if there's a better way of doing it, whether it's too compact, if I should use different data structures, if my comments are too verbose, if my style is alright - basically any kind of tips and advice are very welcome.

from datetime import datetime, timedelta

def process_dates(date):
    """
    Process adjacent days to account for flights that
    have a different departure day than the day they were
    archived (which is the date contained in the filenames)
    """

    """
    Convert to datetime objects before processing
    This is done so the conversion is less error-prone by
    avoiding edge cases like 1st of Jan, 29th of Feb, y3k, etc
    """
    datetimes = []
    today = datetime.strptime(date, '%Y%m%d')

    """
    Compute the adjacent days, but keeping the order of the elements
    the following: today, yesterday, tomorrow, and the day after tomorrow.
    This is done because the looking up later on is done sequentially
    and the order reflects the probability of being the needed date
    (i.e. it's most probable the needed day is today, so it will stop before
    processing the other days)
    """
    [datetimes.append(today + timedelta(days=i)) for i in [0, -1, 1, 2]]
    return [datetime.strftime(j, '%y%m%d') for j in datetimes]


texts:
I wrote a Mongoose Node/Express application. I have 4 documents. I am trying to write a route (end point) to get all seats for a table with their full data. I get a response like I expect.

I want to know if there is a better way to write the application like this.

seat.model.js

const mongoose = require('mongoose');
const SeatScheme = mongoose.Schema({
    table: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Table',
        required: true
    },
    event: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Event',
        require: true
    }
});

module.exports = mongoose.model('Seat', SeatScheme);

course.model.js

const mongoose = require('mongoose');
const CourseSchema = mongoose.Schema({
    seat: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Seat'
    },
    meal: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Meal'
    }
});

module.exports = mongoose.model('Course', CourseSchema);

meal.model.js

const mongoose = require('mongoose');

const MealSchema = mongoose.Schema({
    name: String,
    img: String,
    category: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Category'
    }
});

module.exports = mongoose.model('Meal', MealSchema);

category.model.js

const mongoose = require('mongoose');

const CategorySchema = mongoose.Schema({
    displayname: String,
    type: String
});

module.exports = mongoose.model('Categoty', CategorySchema);

seat.route.js

const Seat = require('../../models/seat/seat.model');
const Course = require('../../models/course/course.model');
const Meal = require('../../models/meal/meal.model');
const Category = require('../../models/category/category.model');

module.exports = function (Router) {
    Router.get('/seats/:tableid', (req, res) => {

        Seat.find({ table: req.params.tableid }, (err, seats) => {
            const seatsPromise = seats.map(seat => {
                return Course.find({ seat: seat._id }).then((courses) => {
                    return Promise.all(courses.map(course => {
                        return Meal.findOne({ _id: course.meal }).then(meal => {
                            return Category.findOne({ _id: meal.category}).then(category => {
                                return {
                                    displayname: category.displayname,
                                    type: category.type,
                                    meal: meal
                                }
                            })
                        })
                    })).then( courses => {
                        return {
                            seat: seat._id,
                            courses: courses
                        };
                    });
                })
            });

            Promise.all(seatsPromise).then(seats => {
                res.json(seats);
            })
        })
    });
}


texts: Boolean enums: improved clarity or just overkill?

texts:
Suppose we are writing a GUI toolkit in C++ (though this question may also apply to other languages). We have a button class with a member function hide, which hides the button. This member function takes a Boolean parameter animated to control if the button should be hidden with an animation.

class Button {
public:
  // Rule of three, etc…

  void hide(bool animated);
};

When invoking this member function, it may not be clear what it does.

Button button;
button.hide(false); // well, does it hide the button or not?
                    // what does "false" even mean here?!

We could rewrite this using a Boolean enum.

class Button {
public:
  // Rule of three, etc…

  enum Animated : bool {
    Animate = true,
    DoNotAnimate = false,
  };
  void hide(Animated animated);
};

Now if we call it, everything becomes more clear.

Button button;
button.hide(Button::DoNotAnimate);

Is this a good thing to do? Does it improve clarity of the code, or is it just overkill and should we use separate documentation (Doxygen-like) for this instead?


texts:
Learn You a Haskell mentions the partition function:

  partition takes a list and a predicate and returns a pair of lists.
  The first list in the result contains all the elements that satisfy
  the predicate, the second contains all the ones that don't.

How's my implementation? I'd prefer to avoid the ++ function, but I'm not sure how to avoid it here.

partition' :: (a -> Bool) -> [a] -> ([a], [a])
partition' f []     = ([], [])
partition' f ys = partition'' f ys [] []
                       where partition'' f [] as bs = (as, bs)
                             partition'' f (x:xs) as bs
                               | f x       = partition'' f xs (as ++ [x]) bs
                               | otherwise = partition'' f xs as (bs ++ [x])


texts: Interactive Linux upgrade script - Follow-up #1

texts:
One year ago I asked for a yearly revision of my Interactive Linux upgrade script.

There is nothing new to the conditions, therefore please read the original question before you decide to comment and / or vote to close as unclear.

Additional notes:

The script will always run interactively as I want to have full control.
The script will be placed on 3 machines only, so I don't need much of generalization.
As my POSIX shell scripting abilities get better, I would very much like to get further incentives.

Edited slightly to avoid echo and to provide some information about the system and hardware. You can answer my original question if you are already in progress of writing it. No problem with that.

#!/bin/sh

set -o nounset

# friendly computer description
readonly computer_description='Vlasta - Laptop - Main'

# color definitions
readonly bold=$(tput bold)
readonly bold_red=${bold}$(tput setaf 1)
readonly bold_green=${bold}$(tput setaf 2)
readonly bold_yellow=${bold}$(tput setaf 3)
readonly bold_blue=${bold}$(tput setaf 4)
readonly bold_magenta=${bold}$(tput setaf 5)
readonly bold_cyan=${bold}$(tput setaf 6)
readonly bold_white=${bold}$(tput setaf 7)
readonly nocolor=$(tput sgr0)

# to create clear blocks of texts, we separate them with this
readonly block_separator='----------------------------------------'

step_number=0
execute_jobs()
{
    # process the given arguments as pairs
    while [ "${#}" -gt 1 ]
    do
        # increase and print the step number along with description
        step_number=$((step_number + 1))
        printf '%s\n' "Step #${step_number}: ${bold_green}${1}${nocolor}"

        # print the command to be run
        printf '%s\n' "Command: ${bold_yellow}${2}${nocolor}"

        printf '%s\n' "${bold_white}${block_separator}${nocolor}"

        # run the actual command
        # ShellCheck mistakenly things we should double quote the parameter
        # if we did, it would become a string and we'd get command not found
        # shellcheck disable=SC2086
        if sudo ${2}
        then
            printf '\n'
        else
            printf '%s\n\n' "${bold_red}An error occurred.${nocolor}"
            exit 1
        fi

        # move to another pair of arguments
        shift 2
    done
}

distro_name=$(lsb_release --id | awk '{ print $3 }')
release_version=$(lsb_release --release | awk '{ print $2 }')
hostname=$(cat /etc/hostname)

printf '\n%s\n' "Friendly: ${bold_magenta}${computer_description}${nocolor}"
printf '%s\n' "Distro  : ${bold_magenta}${distro_name} ${release_version}${nocolor}"
printf '%s\n' "Hostname: ${bold_magenta}${hostname}${nocolor}"
printf '%s\n\n' "${bold_white}${block_separator}${nocolor}"

# the sudo password request shall proceed AFTER computer / hostname
# this is because the same script will always run in sequence on 3 computers
if [ "$(id --user)" -ne 0 ]
then
    sudo sh -c ":" || exit 1
fi

printf '%s' "${bold_cyan}"
sudo dmidecode --type 1 | grep 'System Information' --after 8
printf '%s\n\n' "${bold_white}${block_separator}${nocolor}"

# execute all jobs in one go
execute_jobs \
    'configure packages'                         'dpkg --configure --pending' \
    'fix broken dependencies'                    'apt-get --fix-broken install' \
    'update cache'                               'apt-get update' \
    'upgrade packages'                           'apt-get upgrade' \
    'upgrade packages with possible removals'    'apt-get dist-upgrade' \
    'remove unused packages'                     'apt-get --purge autoremove' \
    'clean up old packages'                      'apt-get autoclean'


texts:
I have code that reads from files of surnames, female and male names and randomly generates a name in the following format: lastname, male/female name.

The files are in the following format:

  JAMES    3.318    4,840,833 1

I have the following working code:

def picks(filename):
    with open(filename) as f:
        lines = [line.strip('\n') for line in f]
        pick = randint(0, len(lines))
    return lines[pick].split()[0]

def random_name(number_of_names):
    nselect = ''
    for _ in range(1, number_of_names+1):
        g = randint(0,1)
        if g==1:
            nselect = picks('femalenames.txt')
        else:
            nselect = picks('malenames.txt')
        print(g)
        print( '{0:s}, {1:s}\n'.format(picks('surnames.txt'), nselect))

random_name(5)

The code generates the correct output but I feel the code could be trimmed a bit.


texts:
I have a method that finds 3 numbers in an array that add up to a desired number.

public static void threeSum(int[] arr, int sum) {
    quicksort(arr, 0, arr.length - 1);
    for (int i = 0; i < arr.length - 2; i++) {
        for (int j = 1; j < arr.length - 1; j++) {
            for (int k = arr.length - 1; k > j; k--) {
                if ((arr[i] + arr[j] + arr[k]) == sum) {
                    System.out.println(Integer.toString(i) + "+" + Integer.toString(j) + "+" + Integer.toString(k) + "="  + sum);
                }
            }
        }
    }
}

I'm not sure about the big O of this method. I have a hard time wrapping my head around this right now. My guess is O(n2) or O(n2logn). But these are complete guesses. I can't prove this. Could someone help me wrap my head around this?


texts:
From https://www.codeeval.com/browse/115/:

  You have a string of words and digits divided by comma. Write a program which separates words with digits. You shouldn't change the order elements.

I tried to do it using Haskell (learning Haskell).

Can you give me some good practices/shortcuts/advice on how to make this code better?

{-# LANGUAGE OverloadedStrings #-}
import qualified Data.Text as T
import System.Environment (getArgs)

main = do
    args <- getArgs
    content <- readFile(args !! 0)
    let fileLines = lines content
    mapM (\x -> putStrLn (mixedContent (generateContent (wordsWhen (==',') x)) [] [])) fileLines

data Content =  String String | Num Int deriving (Show)

generateContent :: [String] -> [Content]
generateContent [] = []
generateContent (x:xs) = if isNumeric x then [(Num (read x))] ++ generateContent xs else [String x] ++ generateContent xs

mixedContent :: [Content] -> [Int] -> [String] -> String
mixedContent  [] d w = foldl (\r x -> r ++ x) "" $ giveResults (generateCommaDelimitedList w) ["|"]  (generateCommaDelimitedList (intToChar d))
mixedContent  ((String x):xs) d w = mixedContent xs d (w ++ [x])
mixedContent  ((Num x):xs) d w = mixedContent xs (d ++ [x]) w

giveResults :: [String] -> [String] -> [String] -> [String]
giveResults [] _ [] = []
giveResults [] _ d = d
giveResults w _ [] = w
giveResults w delimitor d = w ++ delimitor ++ d

intToChar :: [Int] -> [String]
intToChar l = map (\i -> show i) l

generateCommaDelimitedList :: [String] -> [String]
generateCommaDelimitedList [] = []
generateCommaDelimitedList (x:[]) = [x]
generateCommaDelimitedList (x:xs) = (x ++ ","):(generateCommaDelimitedList xs)

isInteger s = case reads s :: [(Integer, String)] of
  [(_, "")] -> True
  _         -> False

isDouble s = case reads s :: [(Double, String)] of
  [(_, "")] -> True
  _         -> False

isNumeric :: String -> Bool
isNumeric s = isInteger s || isDouble s

-- split string equivalent
wordsWhen :: (Char -> Bool) -> String -> [String]
wordsWhen p s =  case dropWhile p s of
                    "" -> []
                    s' -> w : wordsWhen p s''
                            where (w, s'') = break p s'

EDIT: I follow advice given in the answer. I just wanted to show how the main should be to respect what the exercise was asking.

main = do
    args <- getArgs
    content <- readFile(args !! 0)
    let l = lines content
    let lf = filter (\x -> length x > 0) l
    mapM_ (putStrLn . arrange) lf

The interesting part is mapM_, which makes me able to print the lines re-arranged and ignore the result returned by the mapM


texts:
I have a little dilema with such if statement, I have tried optimizing it in order to remove some checks, but could not think of how to make this code part cleaner. Can someone please make a review, and tell if it's possible to optimize such statement of maybe there is some law for this? Thank you

//letter = 'E' or 'R' ( char )
//second letter = 'Q' or 'A' ( char )
//DoFlip = false or true ( bool )

if((letter == 'E' && secondLetter == 'Q' && DoFlip == false)    ||
       (letter == 'E' && secondLetter == 'A' && DoFlip == true) ||
       (letter == 'R' && secondLetter == 'Q' && DoFlip == false)||
       (letter == 'R' && secondLetter == 'A' && DoFlip== true))
    {
      //DoSmth here
    }


texts:
I'm playing around with trying to do things in a better way, and in a class I have for sending emails, I have the concept of a recipient. This gets passed into my other classes essentially as a struct that is a little more descriptive than an associative array.

I'd like to know if the Recipient is going to be valid to pass to the rest of my code, and hence want a way to determine if the email address has any basic errors in it. (I'm aware that validating emails can only be done by sending them an email, for the purposes of this, just ignore this fact!)

Anyway, I have this class that looks like this:

class Recipient
{
    public $email_address, $name;

    public function __construct($email_address, $name) {
        $this->email_address = $email_address;
        $this->name = $name;
    }

    function emailIsValid() {
        return filter_var($this->email_address, FILTER_VALIDATE_EMAIL);
    }

    public function isValid() {
        return ($this->emailIsValid() && $this->name != '');
    }
}

And I'm calling it like:

$recipient = new Recipient('test@example.com', 'Example Name');

then, later when I'm about to send an email to something I can run:

if ($recipient->isValid()) {
    // add to the list of recipients
}

I'm interested on all and any feedback on this - I'm not that confident that this is a 'good' way to do things because:

This class doesn't really do anything, and is really a pretty struct
The validation isn't specific to this place, I may want to check emails in other places
Should the validation happen in the constructor? Should it be a separate class? What would that look like?
Should there be an interface for every class? Would that live at the top of this file?
Should I throw exceptions when it's not valid? Should they be an object as well? How?


texts:
A little disclaimer: you're going to have a field day with this. It's horrible. Looking at it makes me want to vomit, and don't ask me to explain it, because I've long forgotten what I was thinking when I wrote it. That being said, I can't really find a way to shorten it of make it make sense. Perhaps someone could help me out?

A bit of a background:

This program is meant to install mods for a game called Supreme Commander 2. It is meant to install ANY mod. The following is true of all the mods:

The only archive type is the .scd. SCD's have the same encoding as .zip's, but with a 0% compression rate.
The way to install the mod is simple: There will always be at least one scd inside the first, and there may be more scd's inside that one. Any scd with folders inside it should be moved to

  C:\Program Files (x86)\Steam\steamapps\common\supreme commander 2\gamedata

There may be more than one scd to be moved per mod.

And that's it. This is something of a "programming challenge," but I am really looking for improvements upon the following code:

import os, zipfile
def installfromdownload(filename):
    global scdlist
    targetfolder = r"C:\Program Files (x86)\Mod Manager\Mods\f_" + filename[:-4]
    lentf = len(targetfolder)
    unzip(r"C:\Program Files (x86)\Mod Manager\Mods\z_" + filename + ".scd", targetfolder)
    if checkdirs(targetfolder) == False:
        os.system("copy C:\Program Files (x86)\Mod Manager\Mods\z_" + filename + ".scd" " C:\Program Files (x86)\Steam\steamapps\common\supreme commander 2\gamedata")
    else:
        newfolderonelist = []
        getscds(targetfolder)
        for file in scdlist:
            newfolderone = targetfolder + "\f_" + file[:-4]
            filepath = targetfolder + "\\" + file
            unzip(filepath, newfolderone)
            newfolderonelist.append(newfolderone)
        for newfolders in newfolderonelist:
            if os.checkdirs(newfolders) == False:
                newfolders = newfolders[lentf + 1:]
                for scds in scdlist:
                    if newfolder in scds == True:
                        scdpath = targetfolder + "\\" + scds
                        os.system("copy " + scdpath + " C:\Program Files (x86)\Steam\steamapps\common\supreme commander 2\gamedata")

Note that there is no error handling here, that is done when I call the function. The function unzip() is here:

def unzip(file, target):
    modscd = zipfile.ZipFile(file)
    makepath(target)
    modscd.extractall(target)

The function checkdirs() is here (note this is pretty bad, it only checks for periods in the file name, so please submit suggestions):

def checkdirs(target):
    isfile = 0
    targetlist = os.listdir(target)
    for files in targetlist:
        for letters in files:
            if letters == ".":
                isfile = isfile + 1
    if isfile == len(os.listdir(target)):
        return False
    else:
        return True

The getscds() function just checks a filename for ".scd".


texts: Returning nested array with added key=>value

texts:
This works, but do I have to make a new array, result, or is there a way to just insert the field I need into each $key of the received parameter $data?

Won't this way take up more memory needlessly?

function add_tax($data){
            $result = [];
            foreach($data as $product => $details) {
                $details['tax'] = 0;
                $result[$product] = $details;
                }
            return $result;
          }


texts: Base service for two different implementations

texts:
I have code that fetches different templates for HTML and CSS in the file system. The templates are stored in different folders, so I have two implementations for the code that fetches them, passing the correct path as a parameter.

   private string _templatePath;

    private readonly IConfigurationManager _configurationManager;
    private readonly IFileSystem _fileSystem;

    public BaseTemplateFileService(string templatePath,
        IConfigurationManager configurationManager,
        IFileSystem fileSystem)
    {
        _templatePath = templatePath;
        _configurationManager = configurationManager;
        _fileSystem = fileSystem;
    }

    protected abstract string GetExtensionPattern(string templateName);

    public string GetTemplate(string templateName)
    {
        var templatesPath = _configurationManager.GetAppSetting(_templatePath);
        var fullName = GetExtensionPattern(templateName);

        var templatesFolder = _fileSystem.DirectoryInfo.FromDirectoryName(templatesPath);
        var files = templatesFolder.GetFiles(fullName, SearchOption.AllDirectories);
        var totalNumberOfFiles = files.Count();
        if (totalNumberOfFiles < 1)
        {
            throw new PanelException(string.Format("No template file to choose with name: {0}", fullName));
        }
        if (totalNumberOfFiles > 1)
        {
            throw new PanelException(string.Format("Multiple template files to choose with name: {0}", fullName));
        }
        using (var streamReader = files[0].OpenText())
        {
            var content = streamReader.ReadToEnd();

            return content;
        }
    }

public class HtmlTemplateFileService : BaseTemplateFileService
{
    public HtmlTemplateFileService(IConfigurationManager configurationManager,
        IFileSystem fileSystem)
        : base("panelHtmlPath", configurationManager, fileSystem)
    {
    }

    protected override string GetExtensionPattern(string folderName)
    {
        return string.Format("{0}.htm*", folderName);
    }
}

public class CssTemplateFileService : BaseTemplateFileService
{
    public CssTemplateFileService(IConfigurationManager configurationManager,
        IFileSystem fileSystem)
        : base("panelCssPath", configurationManager, fileSystem)
    {
    }

    protected override string GetExtensionPattern(string folderName)
    {
        return string.Format("{0}.scss*", folderName);
    }
}

What I don't like about this approach is that I need to set up my IoC contaier (i.e. Unity) like this

container.RegisterType<CssPanelGenerator>(new InjectionConstructor(
    new ResolvedParameter<ITemplateService>("cssTemplateService"), typeof(CssVariableService), typeof(ProcessSass)));

and same for the HTML one.

Is there a cleaner way to avoid code repetition but without the need to use this slightly more convoluted way of doing dependency injection that I can't think of?


texts:
I have created an open source memory cache called cachew and can be found here:
cachew. I would like your help to make it better.

Regarding the class Cache or its dependencies:

I am thinking of removing timeoutStyle and timeout from the Cache constructor and providing default values that can be changed via public properties. How do you like that?
How do you like my abstraction LockManager for ReaderWriterLockSlim?
Do you think my timer in Cache should be configurable? Through a property in cache, change internal to public or by another method?
Do you think it is a bad practice to start a timer in a constructor? If so, what would you do?
Would you consider the Cache threadsafe? Could it be better implemented?

public enum TimeoutStyle
{
    FixedTimeout,
    RenewTimoutOnQuery
}

public class Cache : ICache
{
    private readonly ITimer expirationTimer;
    private readonly IInternalCache internalCache;

    private readonly LockManager lockManager = new LockManager();

    public Cache(TimeoutStyle timeoutStyle, TimeSpan timeout) :
        this(new InternalCache(timeoutStyle, timeout), new SystemTimer(5000))
    {

    }

    internal Cache(IInternalCache iternalCache, ITimer expirationTimer)
    {
        if (iternalCache == null) throw new ArgumentNullException("iternalCache");
        if (expirationTimer == null) throw new ArgumentNullException("expirationTimer");
        this.internalCache = iternalCache;
        this.expirationTimer = expirationTimer;

        this.expirationTimer.Elapsed += ExpirationTimerElapsed;
        this.expirationTimer.Start();
    }

    public object Get<T>(CacheKey key, Func<T> func)
    {
        using (lockManager.EnterRead())
        {
            object existingValue;
            if (internalCache.TryGetValue(key, out existingValue))
                return existingValue;
        }

        using (lockManager.EnterWrite())
        {
            object existingValue;
            if (internalCache.TryGetValue(key, out existingValue))
                return existingValue;

            var newValue = func();
            internalCache.Add(key, newValue);
            return newValue;
        }
    }

    private void ExpirationTimerElapsed(object sender, EventArgs e)
    {
        using (lockManager.EnterWrite())
        {
            internalCache.RemoveExpiredItems();
        }
    }
}


texts:
I am still getting the hang of Exception Handling in PHP; Here is the scenario where I am using the convention:
There are times where I have a SQL query that I need to turn into an object, so I wrote this utility class/method.

Class A {
    public static function getThatOneInstance(){
        $sql = "SELECT id FROM table WHERE condition=met LIMIT 1";
        $O = UtilsMysql::fetchIdIntoInstance($sql, __CLASS__, new Exception('Not Found!?'));
        return $O;
    }
}

Class UtilsMysql {
    public static function fetchIdIntoInstance($sql, $Class, Exception $NotFoundE = NULL){
        $O = NULL;
        $r = mysql_query($sql);
        if (!$r) throw new ExceptionMySQL($sql);
        if (mysql_num_rows($r) > 0) {
            list($id) = mysql_fetch_row($r);
            $O = new $Class($id);
        } elseif (!is_null($NotFoundE)) {
            throw $NotFoundE;
        }
        return $O;
    }
}

There are times, though, where if there is no result returned from the query it represents an Exceptional Circumstance, and so an Exception needs to be thrown. Because this is not uncommon, rather than always testing the returned value from the utility method, I have started passing in an Exception, that will be thrown if no results are found. This way, I have a contract with the function, if I pass in an exception, I can rely on the fact that it returns an Object (don't need to test it).

Is it acceptable to pass an Exception into a function that then may or may not throw it?


texts:
This is a plug-in which tracks your online activity aka a lifestream. You're currently able to use feeds like:

Delicious
Flickr
Github
Google Reader
Last.fm
Stackoverflow
Twitter
Youtube

At first I decided to load all the feeds at the end of all the asynchronous requests. This only required one DOM request at the end.

The problem with that approach is that it just takes too long to load. Some requests timed-out and others just took a while.

What I'm doing right now is changing the DOM after each feed request (e.g. twitter). At the moment this means 8 DOM changes.

What would be the best practice in this situation? Doing a setTimeout and accessing the dom after e.g. 400ms? Or would you leave it as it is now?

If you have any other remarks or suggestions, those would be appreciated as well.

/**
* Initializes the lifestream plug-in
* @param {Object} config Configuration object
*/
$.fn.lifestream = function(config){

var outputElement = this;

// Extend the default settings with the values passed
var settings = jQuery.extend({
  "classname": "lifestream",
  "limit": 10
}, config),
data = {
  "count": settings.list.length,
  "items": []
};

var finished = function(inputdata){

  $.merge(data.items, inputdata);

  data.items.sort(function(a,b){
      if(a.date > b.date){
          return -1;
      } else if(a.date === b.date){
          return 0;
      } else {
          return 1;
      }
  });

  var div = $('
');

  var length = (data.items.length < settings.limit)
    ? data.items.length
    : settings.limit

  for(var i = 0, j=length; i<j; i++){
    if(data.items[i].html){
      div.append('
'
        + data.items[i].html + "
");
    }
  }

  outputElement.html(div);

}

var load = function(){

  // Run over all the items in the list
  for(var i=0, j=settings.list.length; i<j; i++) {
    var item = settings.list[i];
    if($.fn.lifestream.feeds[item.service] &&
        $.isFunction($.fn.lifestream.feeds[item.service])){

      $.fn.lifestream.feeds[item.service](item, finished);
    }
  }
}

load();

};

Complete code:

https://github.com/christianv/jquery-lifestream/blob/master/jquery.lifestream.js

Documentation:

https://github.com/christianv/jquery-lifestream#readme


texts: Save/Load GridView layout using SettingsService

texts:
I am able to save my GridView layout by storing a string representation of the items in the ItemsSource. I then load that string representation from the SettingsService and set the index of the items accordingly.

The layout is changed by drag/dropping items in the GridView. Here is the code-behind:

private void MainGridView_OnDrop(object sender, DragEventArgs e)
{
    var grid = e.OriginalSource as GridView;
    var items = grid?.ItemsSource as ObservableCollection<AppPage>;

    if (items != null)
    {
        var layout = "";

        // save settings
        foreach (var p in items)
        {
            p.PageIndex = items.IndexOf(p);
            // serialize pagename and pageindex
            layout += $"{p.PageName},{p.PageIndex}|";
        }
        _settings.MainMenuLayout = layout;
    }
}

Then when I load the application, I check for the MainMenuLayout setting and parse it out like so:

public void LoadMainMenu()
{
    var pages = new ObservableCollection<AppPage>
    {
        new AppPage("Payees", "ms-appx:///Assets/payee-180.png", typeof(Views.PayeesPage)),
        new AppPage("Bills", "ms-appx:///Assets/invoice-180.png", typeof(Views.InvoicesPage)),
        new AppPage("Payments", "ms-appx:///Assets/envelope-180.png", typeof(Views.PaymentsPage)),
        new AppPage("Checkbook", "ms-appx:///Assets/checkbook-180.png", typeof(Views.CheckbookPage)),
        new AppPage("Receipts", "ms-appx:///Assets/receipt-180.png", null),
        new AppPage("Categories", "ms-appx:///Assets/categories-180.png", typeof(Views.CategoriesPage)),
        new AppPage("Accounts", "ms-appx:///Assets/bank-180.png", typeof(Views.AccountsPage)),
        new AppPage("Budget", "ms-appx:///Assets/budget-180.png", null),
        new AppPage("Contacts", "ms-appx:///Assets/contacts-180.png", typeof(Views.ContactsPage)),
        new AppPage("Reports", "ms-appx:///Assets/charts-180.png", typeof(Views.ReportsPage)),
        new AppPage("Test", "ms-appx:///Assets/beaker-180.png", typeof(Views.TestPage)),
    };

    var layout = _settings.MainMenuLayout;
    if (!string.IsNullOrEmpty(layout))
    {
        // split on |
        var pagesSplit = layout.Split('|');

        foreach (var p in pagesSplit)
        {
            // then split on ,
            if (p.Contains(","))
            {
                var pageInfo = p.Split(',');
                var cur = pages.First(page => page.PageName == pageInfo[0]);
                cur.PageIndex = int.Parse(pageInfo[1]);
            }
        }
    }

    // sort based on index
    AppPages = new ObservableCollection<AppPage>(pages.OrderBy(p => p.PageIndex));
}

Is there a better way to serialize/deserialize the layout? I don't want to store the entire AppPage objects for every item, as there are additional properties that are unrelated to the layout.


texts: Getting a list of waypoints assuming that there is a map

texts:
I'm a beginner learning ROS. I'm developing an android application that will control my robot and that includes getting the list of waypoints to display it to my spinner. How do you get the list of waypoints to my topic /waypoints assuming that there is a map?

I've already done the code for subscribing to the topic /waypoints and serializing its msg type

This is my code for serializing the msg-type of the topic /waypoints:

public class WaypointList {

    @SerializedName("header")
    @Expose
    public Header header;
    @SerializedName("pose")
    @Expose
    public Pose pose;
    @SerializedName("name")
    @Expose
    public String name;
    @SerializedName("secs")
    @Expose
    public int secs;
    @SerializedName("nsecs")
    @Expose
    public int nsecs;
    @SerializedName("position")
    @Expose
    public Position position;
    @SerializedName("orientation")
    @Expose
    public Orientation orientation;
    @SerializedName("y")
    @Expose
    public float y;
    @SerializedName("x")
    @Expose
    public float x;
    @SerializedName("z")
    @Expose
    public float z;
    @SerializedName("w")
    @Expose
    public float w;
    @SerializedName("stamp")
    @Expose
    public Stamp stamp;
    @SerializedName("frame_id")
    @Expose
    public String frameId;
    @SerializedName("seq")
    @Expose
    public int seq;
    @SerializedName("waypoints")
    @Expose
    public List<WaypointList> waypoints = null;

    /**
     * No args constructor for use in serialization
     *
     */
    public WaypointList() {
    }

    /**
     *
     * @param waypoints
     */
    public WaypointList(List<WaypointList> waypoints, Stamp stamp, String frameId, int seq, float y, float x, float z, float w, Position position, Orientation orientation, int secs, int nsecs, Header header, Pose pose, String name) {
        super();
        this.header = header;
        this.pose = pose;
        this.name = name;
        this.secs = secs;
        this.nsecs = nsecs;
        this.position = position;
        this.orientation = orientation;
        this.y = y;
        this.x = x;
        this.z = z;
        this.w = w;
        this.stamp = stamp;
        this.frameId = frameId;
        this.seq = seq;
        this.waypoints = waypoints;
    }


texts: Given a 2D array of digits, try to find the occurrence of a given 2D pattern of digits

texts:
My algorithm is quite simple. I simply iterate over the entire map arr and if I find the start of the combination I need to find, I begin exploring.

My combination data structure is simply the combination I need to find, column at a time.

If each column in arr matches, I return True. If at any point the value doesn't match the combination I need I return False.

I believe this is O(n+m) time with O(1) space. Code below...

def explore(arr, combination, i, j):
    """
    for each column in the combination we have to find
    compare it with what is present in the map (arr)
    """
    for row in combination:
        for count, item in enumerate(row):

            # compare the map with the combination value we're up to
            # if it doesn;t match, return False and stop
            if arr[i+count][j] != item:
                return False
        j+=1
    return True

def find_combination_in_arr(arr, combination, ):
    for i, row in enumerate(arr):
        for j, item in enumerate(row):

            # if we have found the start of the combination, then start exploring
            if item == combination[0][0]:
                if explore(arr, combination, i, j):
                    return "FOUND IT!"

# the map we need to search
arr = [
    [1, 1, 2, 3, 4, 1, 1],
    [1, 1, 5, 6, 7, 1, 1],
    [1, 1, 2, 7, 4, 1, 1],
    [1, 1, 7, 8, 6, 1, 1]
]

# the combination we need to find
combination = [
    [2, 5, 2, 7],
    [3, 6, 7, 8],
    [4, 7, 4, 6]
]

find_combination_in_arr(arr, combination)


texts:
Today, I created an input class with a method to check whether or not input via GET/POST exists, and another method to retrieve input from either GET/POST, without having to check both individually.

class input {
        public static function exists($type = 'post') {
            switch ($type) {
                case "post":
                    return (!empty($_POST)) ? true : false;
                break;
                case "get":
                    return (!empty($_GET)) ? true : false;
                break;
                default:
                    return false;
                break;
            }

        }

        public static function get($data) {
            if (isset($_GET[$data])){
                return $_GET[$data];
            } else if (isset($_POST[$data])){
                return $_POST[$data];
            } else {
                return '';
            }
        }
    }

Here is my form and example usage:

<?php
    require_once('core/init.php');

    if(input::exists()){
        echo input::get('username');
        echo input::get('password');
        echo input::get('confirm_password');
    }

?>

    <form method="POST" autocomplete="off">

                Username

            <input type="text" name="username" id="username" />

                Password

            <input type="password" name="password" id="password" />

                Confirm Password

            <input type="password" name="confirm_password" id="confirm_password" />

            <input type="submit" />

    </form>

First of all, is it okay for me to access the methods in the way that I have? Is using statics in this way bad practice?

Secondly, aside from what I asked above, are there any recommendations or improvements that you can suggest?


texts:
I have written the below code which generates 4 random, whole integer values between 1 and 6 and then saves the sum of the 3 largest values. It generates a total of 6 values this way, displays the total along with all 6 values once finished.

The order in which each value was generated must be preserved.
The total of all 6 values must be at least 75 or above.
At least 2 of the values must be 15 or more.

import java.util.Random;
import java.util.Arrays;

public class Test {
    static boolean goodRoll = false;

    public static int genAttribute() {

        Random dice = new Random();
        int[] sumArray = {dice.nextInt(6) + 1, dice.nextInt(6) + 1, dice.nextInt(6) + 1, dice.nextInt(6) + 1};
        for (int num : sumArray) {
            System.out.println(num);
        }

        int first = Integer.MIN_VALUE;
        int firstIndex = -1;
        int second = Integer.MIN_VALUE;
        int secondIndex = -1;
        int third = Integer.MIN_VALUE;

        for (int i = 0; i < sumArray.length; i++) {
            int num = sumArray[i];
            if (num > first) {
                first = num;
                firstIndex = i;
            }
        }

        for (int i = 0; i < sumArray.length; i++) {
            int num = sumArray[i];
            if (num > second && num <= first && i != firstIndex) {
                second = num;
                secondIndex = i;
            }
        }

        for (int i = 0; i < sumArray.length; i++) {
            int num = sumArray[i];
            if (num > third && num <= second && i != secondIndex && i != firstIndex) {
                third = num;
            }
        }
        System.out.println(first + " " + second + " " + third);

        return first + second + third;

    }

    public static boolean checkFinalArray(int[] checkArray) {
        int fifteenCount = 0;
        for (int z : checkArray) {
            if (z >= 15) {
                fifteenCount++;
            }
        }

        return (fifteenCount >= 2 && Arrays.stream(checkArray).sum() >= 75);
    }

    public static void main(String[] args) {

        while (!goodRoll) {
            int[] finalArray;
            finalArray = new int[6];

            for (int i = 0; i < 6; ++i) {
                finalArray[i] = genAttribute();
            }

            if (checkFinalArray(finalArray)) {
                System.out.println("sum: " + Arrays.stream(finalArray).sum());
                // Enhanced for to print each die
                for (int x : finalArray) {
                    System.out.println(x);

                }
                goodRoll = true;
            }
        }
    }

}

Can this be more efficiently written?