Relative relationships This is a question in Udacity JS course. I am starting to like Javascript. I feel its a misunderstood language :)

  We learned about relational operators and how they can classify the
  relationship between two values.  Your job is to write the function
  getRelationship(x,y) function, which should return a string
  representing whether x is >, < or = y. For example:

var rel = getRelationship(2, 3);
console.log(rel); // <

  If one or both of the values aren't numbers, your function should
  output:

    "Can't compare relationships because [this value] and [that value] [is]/[are] not [a] number[s]."

  where [this value] and [that value] are replaced with the
  non-numerical values. The sentence should be grammatically correct by
  outputting either is or are and pluralizing number if necessary.

  For example:

var rel1 = getRelationship("this", 2);
console.log(rel1); // "Can't compare relationships because this is not a number"

var rel2 = getRelationship("that");
console.log(rel2) // "Can't compare relationships because that and undefined are not numbers"

  Notice in the second example, because the y value was missing, the
  output said that undefined was not a number.

Here is my stab at the solution.

function getRelationship(x, y) {
    var respObj = validateArgAsNumber(x,y);
    if (respObj.x && respObj.y && !respObj.isXNaN && !respObj.isYNaN) {
        console.log("Both are numbers");
        if (x > y) {
            return ">";
        } else if (x < y) {
            return "<";
        } else {
            return "=";
        }
    } else {
        console.log("Both are NOT numbers");
        //console.log(respObj);
        if ((!respObj.x && !respObj.y) || (respObj.isXNaN && respObj.isYNaN)){
            return "Can't compare relationships because " + x + " and " + y + " are not numbers";
        }
        if (!respObj.x || respObj.isXNaN) {
            return "Can't compare relationships because " + x + " is not a number";
        }
        if (!respObj.y || respObj.isYNaN) {
            return "Can't compare relationships because " + y + " is not a number";
        }
    }
}

function validateArgAsNumber(a,b) {
    var response = {};
    response.isXNaN = isNaN(a);
    response.isYNaN = isNaN(b);
    response.x = typeof(a) == 'number';
    response.y = typeof(b) == 'number';
    return response;
}

console.log(getRelationship(1,4));
console.log(getRelationship(1,1));
console.log(getRelationship("that",2));
console.log(getRelationship("this"," something else"));
console.log(getRelationship(3));
console.log(getRelationship("hi"));
console.log(getRelationship(NaN, NaN));
console.log(getRelationship(NaN));
console.log(getRelationship(NaN, undefined));

I'm confused as to why you treat the results of isNaN and typeof as separate things, since failing either test would invalidate the argument.

So you could simplify validateArgAsNumber a lot if you just gave it one argument and let it return a simple boolean. Its name actually already implies only one argument, since it's called "validate arg", not "validate args". However, I'd rather call it isValidNumber - why care if it's an argument for something else?

function isValidNumber(value) {
    return typeof value === 'number' && !Number.isNaN(value);
}

If typeof value isn't 'number', we immediately know something's wrong. The isNaN check is only necessary because JavaScript has this funny thing about NaN itself being a number (it's a long story and has to do with IEEE-754 64-bit floating point numbers).

From there, the rest of the code becomes a lot simpler, since you don't have to worry about checking two separate booleans each time you want to check one argument.

I'd also be tempted to simply make the validation function an inner function in getRelationship, since its purpose is somewhat specific to that task.

Of course, the function is now so simple that it almost doesn't need to be a function, but let's roll with it. It avoids a trivial bit of repetition.

With the above you might get something like this:

function getRelationship(x, y) {
  function isValidNumber(value) {
    return typeof value === 'number' && !Number.isNaN(value);
  }

  var xValid = isValidNumber(x),
      yValid = isValidNumber(y);

  if(!xValid && !yValid) {
    return "Can't compare relationships because " + x + " and " + y + " are not numbers";
  }

  if(!xValid || !yValid) {
    return "Can't compare relationships because " + (xValid ? y : x) + " is not a number";
  }

  if(x === y) {
    return '=';
  }

  return x < y ? '<' : '>';
}

Note that I've combined the check for "x or y is invalid" into a single return. That way, I don't have to repeat a line of mostly-hardcoded text.

The last bit - after checking the arguments - can be handled in many ways. I chose the above, because it puts an explicit return on the last line, which I think reads well. It only returns early from inside a branch if it has to. But you could of course also use if..else if..else, or even a switch:

switch(true) {
  case x > y: return '>';
  case x < y: return '<';
  default: return '=';
}

But that's a little too tricky.


Code duplication when converting DTO to String messages In a payment application a day before and at the same time with some payments some messages(email) needs to be sent.
I have a DTO (called EscrowPayment, projected from some entity) from which I generate and send two similar `messages.

I look for advice specifically on the following issues with the code I ended up:

Copy-pasted code.
Type suffix in identifiers. eg: nominalAmountStr
Static utility methods formatInteger etc (Used application wide).
String constants in code. But because they are parameterized by position and not by name; if I extract them to a configuration file as they are,
I wouldn't know in which order I should be giving parameters to String.format.

Here is the code; it is sanitized and translated, but issues are clearly identifiable:

public class EscrowPaymentMessageServiceImpl {

    private JavaMailSender mailSender;

    // .....

    @Override
    public void escrowPaymentWillBeDone(EscrowPayment escrowPayment) throws BusinessLayerException {
        try {
            String nominalAmountStr = formatInteger(new BigDecimal(escrowPayment.getNominal()));
            String paymentDateStr = dateFormat(escrowPayment.getPaymentDate(), "dd/MM/yyyy");
            String interestRateStr = format(escrowPayment.getInterestRate(), "0.00###");
            String paymentAmountStr = format(escrowPayment.getPaymentAmount());
            String messageText = String
                    .format("BLAH BLAH some security with ID %s of nominal value EUR %s "
                            + "at date %s BLAH your account with number 1234567890 will be debited to pay "
                            + "EUR %s coupon payment for %%%s interest.",
                            escrowPayment.getSecurityId(), nominalStr, paymentDateStr,
                            interestRateStr, paymentAmountStr);

            sendMessage(messageText);
        } catch (MessagingException e) {
            getLog().error("An error occured while sending the email:", e);
            throw new BusinessLayerException("EscrowPaymentMessage.MessageCouldNotBeSent", e);
        }
    }

    @Override
    public void escrowPaymentIsDone(EscrowPayment escrowPayment) throws BusinessLayerException {
        try {
            String nominalAmountStr = formatInteger(new BigDecimal(escrowPayment.getNominal()));
            String paymentDateStr = dateFormat(escrowPayment.getPaymentDate(), "dd/MM/yyyy");
            String paymentAmountStr = format(escrowPayment.getPaymentAmount());
            String messageText = String.format("BLAH BLAH at date %s the security with ID %s of nominal value EUR %s "
                            + "BLAH your account with number 1234567890 has been debited to pay EUR %s." ,
                            paymentDateStr, escrowPayment.getSecurityId(), nominalStr, paymentAmountStr);

            sendMessage(messageText);
        } catch (MessagingException e) {
            getLog().error("An error occured while sending the email:", e);
            throw new BusinessLayerException("EscrowPaymentMessage.MessageCouldNotBeSent", e);
        }
    }

    private void sendMessage(messageText) throws MessagingException {
        //....
    }

}

This strikes me as an occasion where a custom method with positional format indexing may help (Formatter argument_index). It is a little-known feature of Java's String.format / Formatter class, that you can reference values by their position. Consider the following methods:

@Override
public static final String formatEscrowPayment(String format, EscrowPayment escrowPayment) {
        String nominalAmountStr = formatInteger(new BigDecimal(escrowPayment.getNominal()));
        String paymentDateStr = dateFormat(escrowPayment.getPaymentDate(), "dd/MM/yyyy");
        String interestRateStr = format(escrowPayment.getInterestRate(), "0.00###");
        String paymentAmountStr = format(escrowPayment.getPaymentAmount());
        return String.format(format,
                        escrowPayment.getSecurityId(), // 1
                        nominalStr,                    // 2
                        paymentDateStr,                // 3
                        interestRateStr,               // 4
                        paymentAmountStr);             // 5

}

private static final void sendExcrowMessage(String template, ExcrowPayment escrow) throws BusinessLayerException {
    try {
        String messageText = formatEscrowPayment(template, escrow);
        sendMessage(messageText);
    } catch (MessagingException e) {
        getLog().error("An error occured while sending the email:", e);
        throw new BusinessLayerException("EscrowPaymentMessage.MessageCouldNotBeSent", e);
    }
}

@Override
public void escrowPaymentWillBeDone(EscrowPayment escrowPayment) throws BusinessLayerException {
    sendEscrowMessage("BLAH BLAH some security with ID %1$s of nominal value EUR %2$s "
                    + "at date %3$s BLAH your account with number 1234567890 will be debited to pay "
                    + "EUR %5$s coupon payment for %%%4$s interest.",
                      escrowPayment);

@Override
public void escrowPaymentIsDone(EscrowPayment escrowPayment) throws BusinessLayerException {
        sendEscrowMessage("BLAH BLAH at date %3$s the security with ID %1$s of nominal value EUR %2$s "
                        + "BLAH your account with number 1234567890 has been debited to pay EUR %2$s." ,
}

Note how the substitution values are handled by their positions.... the %1$s references the first format value as a string. The %3$s references the 3rd value. You can change the order of the positional fields without having to change the positions of the values in the actual format call. Have a look at the documentation


Swap Nodes in Pairs in singly linked list Description:

Given a linked list, swap every two adjacent nodes and return its head.

  For example, Given 1->2->3->4, you should return the list as
  2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

Code:

class Solution {
    public ListNode swapPairs(ListNode head) {

        if (head == null || head.next == null) {
            return head;
        }

        ListNode current = head;
        ListNode prev = null;
        ListNode newHead = head.next;

        while (current != null && current.next != null) {

            ListNode first  = current;
            ListNode second = current.next;

            first.next = second.next;
            second.next = first;

            // check if its not the first pair
            if (prev != null) {
                prev.next = second;
            }

            // update pointers
            current = second;
            prev = current.next;
            current = current.next.next;
        }
        return newHead;
    }
}

Questions:

The above code passes all tests, the main struggle was the swapping logic and only after I chose meaningful names first and second I was able to clear my thoughts and move forward. Again I see that the linked list involves a lot of edge cases specially managing pointers.

I would like to know if there are some good to know points to avoid common mistakes in linked lists.

PS: Other feedbacks are welcomed too

Once again, splitting this into different parts would benefit the solution. Basically:

A method, which swaps the first two elements in a given list if there are at least two elements. Then return the new first element. (Just return the one element if there is only one.)
A method which iterates: call the first method on the list head, then advance the current pointer twice, then call the method again and update the next pointer of the current node. Repeat until finished.

In general: always try to split a problem into parts which you can tackle separately.

Due to the comments below, I feel compelled to break my personal rule of not just posting code. Thus, here's a working (not thorougly tested) approach which uses the idea presented above. I hope that makes it clearer. (Note: succ == successor, that is the naming I learned at scool a long time ago...)

private static <T> ListNode<T> pairSwapHead(ListNode<T> head) {
    if(head == null || head.succ == null)
        return head;
    ListNode<T> next = head.succ;
    head.succ = next.succ;
    next.succ = head;
    return next;
}

private static <T> ListNode<T> pairSwapList(ListNode<T> head) {
    ListNode<T> curr = pairSwapHead(head);
    ListNode<T> res = curr; // result of first swap is new head == return value

    while(curr != null && curr.succ != null) {
        // second node of the current pair, which needs the next pointer
        // adjusted after the sublist starting at offset 2 gets swapped
        ListNode<T> needsNewNext = curr.succ;
        curr = curr.succ.succ;     // advance to sublist at offset two
        curr = pairSwapHead(curr); // swap first two elements
        needsNewNext.succ = curr;  // and adjust the pointer
    }
    return res;
}


Java util to compare if time beyond cutoff I have a to write a simple utility function that given a time in CST and a date in PST, tells if the date is today and if the current time is less than the cutoff (post converting cutoff to PST).

This is my attempt (highly childish but I seriously don't get Java date-time at all). If anyone could help me improve this code, I would be highly grateful.

  /**
   * Returns true if:
   *   - availableDate is today
   *   - currentTime is less than cutoff time
   * False otherwise
   *
   * @param cutoffTimeStr HH:mm format, CST timezone
   * @param availableDate YYYYMMDD format, PST timezone
   * @return true/false
   */
  public Boolean test(String cutoffTimeStr, String availableDate) throws ParseException{
    DateFormat availableDateFormat = new SimpleDateFormat("YYYYMMDD", Locale.ENGLISH);
    Date avlDate = availableDateFormat.parse(availableDate);
    avlDate.setHours(new Date().getHours());
    avlDate.setMinutes(new Date().getMinutes());
    //Compose current time with the given date

    DateFormat cutOffFormat = new SimpleDateFormat("HH:mm");
    cutOffFormat.setTimeZone(TimeZone.getTimeZone("CST"));
    Time cutOffTime = new java.sql.Time(cutOffFormat.parse(cutoffTimeStr).getTime());
    //cutOffTime is PST version of given CST time

    Date currentDateWithCutoffTime = new Date();
    currentDateWithCutoffTime.setHours(cutOffTime.getHours());
    currentDateWithCutoffTime.setMinutes(cutOffTime.getMinutes());
    //Today's date with time as cutoff

    if(avlDate.before(currentDateWithCutoffTime)){
      return true;
    } else{
      return false;
    }
  }

I have assumed that the availableDate will always be today or greater than today and thus, if its before the currentDateWithCutoffTime, we can return true.

You can shorten this:

if(avlDate.before(currentDateWithCutoffTime)){
    return true;
} else{
    return false;
}

to this:

return avlDate.before(currentDateWithCutoffTime);

It'll automatically return whichever conditional is returned by the method.


Fisher-Yates shuffle in JavaScript This is my first time making a function just from reading about it on Wikipedia, so I'm sure there's room for a lot of improvement.

function fisherYates(str) {
  let result = '';
  for (let i = 0, len = str.length; i < len; i++) {
    let rand = (Math.random()*str.length)|0;
    result += str[rand];
    str = str.slice(0, rand) + str.slice(rand+1);
  }
  return result;
}

Mostly just style
Why add the variable len inside the for loop. It is a constant so put it outside the loop as one.
The variable result is in function scope. Use var rather than let.
The variable rand does not change inside the loop so it should be a const.
The expression to get the random number does not need the (...) as operator precedence ensures that the | is applied correctly.
Add some spaces between operators for readability. eg (Math.random()*str.length)|0; is better as (Math.random() * str.length) | 0
One issue
The only problem is that you have one to many iterations. The last random value will always be to select from a 1 character string, so it is not needed. You need only iterate the string length minus one.
The rewrite
How I would rewrite your code. I personally don't like putting the let inside the for loop, so I put the declaration in the scope above. This is because for loops can have a lot of noise (clutter) and that reduces it a bit. Also the function is so short and simple variable names can be shortened without problem, I would make rand just the r.
function fisherYates(str) {
  var i, result = '';
  const len = str.length - 1;
  for (i = 0; i < len; i ++) {
    const r = Math.random() * str.length | 0;
    result += str[r];
    str = str.slice(0, r) + str.slice(r + 1);
  }
  return result + str;
}


Parsing a string containing arithmetic operations in prefix notation This is a piece from the complete program.
What it does is parses mathematical expressions of the form (+(*3,x),5) to 3*x + 5 and store it in an object of class Formula. Add,Mul, Div, Exp, X, Integer and Symbols are derived from Formula class. Recursive strategy has been used to parse formulae with greater complexity.

Please request for any other piece of code if required.

Does this code have redundancy? How can it be improved?

void parse(Formula*& f, string s, int &k)
{
    if(s[k] == '(')
    {
        k++;
        if(s[k] == '+')
        {
            f = new Add();
        }
        else if(s[k] == '/')
        {
            f = new Div();
        }
        else if(s[k] == '-')
        {
            f = new Sub();
        }
        else if(s[k] == '*')
        {
            f = new Mul();
        }
        else
        {
            f = new Exp();
        }

        k++;
        parse(f->left, s, k);
        k = k + 2;
        parse(f->right, s, k);
        k++;
    }
    else
    {
        if(s[k] == 'x')
        {
            X* a = new X();
            f = a;
        }
        else if(48 <= s[k] <= 57)
        {
            Integer* a = new Integer();
            a->i = s[k] - 48;
            f = a;
        }
    }
}

First, since you're parsing strings at the character level, you could cast the character to an int and utilize a switch statement to check the values (vs. an else if which checks each branch), e.g. switch (static_cast<unsigned int>(s[k])). Also, unless there's a specific need, it's advisable to prefer the pre-increment vs. post-increment operators, e.g. ++k vs. k++. These 2 changes are for speed optimizations (since you are doing parsing). For the static_cast of the char type, strictly speaking, you do not need the explicit cast to an int type, that's there for explicitness (pedant/completeness/explanation) since switch statements only work on integral types, thus any type that can be converted is (either implicitly by the compiler, or explicitly by the user).

Also, there's a logic bug in your code, the line that reads else if(48 <= s[k] <= 57) will always be true. This line evaluates to the following: else if ((48 <= s[k]) <= 57) .. take note of the added parenthesis. Essentially you're asking if a boolean value is <= 57 which is always true. This line should read as such: else if ((48 <= s[k]) && (s[k] <= 57)).

The following is the updated code:

void parse(Formula*& f, std::string s, int &k)
{
    switch (static_cast<unsigned int>(s[k])) // explicit cast
    {
        case '(':
        {
            switch (s[++k]) // implicit cast
            {
                case '+': f = new Add(); break;
                case '/': f = new Div(); break;
                case '-': f = new Sub(); break;
                case '*': f = new Mul(); break;
                default:  f = new Exp(); break;
            }
            parse(f->left, s, ++k);
            k = k + 2;
            parse(f->right, s, k);
            ++k;
        } break;
        case 'x':
            f = new X();
            break;
        default:
            if ((48 <= s[k]) && (s[k] <= 57)) {
                f = new Integer();
                (static_cast<Integer*>(f))->i = s[k] - 48;
            }
            break;
    }
}

Again, I don't have your complete code so these semantics might need to be adjusted for your specific case, but in general this cuts down branch prediction and temporary usage (which the compiler can then optimize further).

Hope that can help.


Java recursive sort verification function for a linked list It should return true, if there is no element that follow or the following elements are greater than their predecessors.
public class Element {
    private int value;
    private Element next;

    public boolean isSorted(){
        if (this.next == null)
            return true;
        else return (this.value < this.next.value && this.next.isSorted());
    }
}

What do you guys think of it?

I would like to add few improvements for better readability.

You don't need an else statement; rather you should directly return it.

For every if and else statement, even if it is a single line and Java allows it without braces, it's not preferable because of possible code bugs which may arise in future due to missing braces.

Better to put (this.value < this.next.value) in brackets for better readability.

So the updated code should look like:
public boolean isSorted() {
    if (this.next == null) {
        return true;
    }

    return (this.value < this.next.value) && this.next.isSorted();
}


Histogram word counter in Python I would like to ask for code review for my Python histogram word counter.

# Given a body of text, return a hash table of the frequency of each word.

"""

# I use a hash map as my data structure to create the histogram
# and add words into the dictionary
# if words are not in the dictionary, then I add those word into the dictionary
# final output is that we return the dictionary
"""

# Word Counter

# Given an body of text, return a hash table of the frequency of each word.

# Parameters
# Input: text {String}
# Output: {Hash Table}

# Constraints
# Capital and lower case versions of the same word should be counted is the same word.
# Remove punctuations from all words.
# Time: O(N)
# Space: O(N)
# Where N is the number of characters in the string.

# Examples
# 'The cat and the hat.' --> '{ the: 2, cat: 1, and: 1, hat: 1 }'`
# 'As soon as possible.' --> '{ as: 2, soon: 1, possible: 1 }'`
# 'It's a man, it's a plane, it's superman!' --> '{ its: 3, a: 2, man: 1, plane: 1, superman: 1 }'`

def word_count(sentence):
    word_counter = {}
    wordlist = sentence.lower().split()
    for word in wordlist:
        word = re.sub('[.,:*! ]', '', word)

        if word in word_counter:
            word_counter[word] += 1
        else:
            word_counter[word] = 1
    return word_counter

example = word_count("It's a man, it's a plane, it's superman!")

Several things can be improved in your existing code. First and foremost being, replacing your usage of re module. Regex matching is very heavy. You have a defined set of characters being replaced. Use str.replace or str.translate.

You have provided comments aptly throughout the program. However, you can place them as docstring for the function, including the examples as doctests. There are several syntaxes to format docstrings. I am mostly aware of epytext and reStructuredText. You can search around for other common formats :).

You'll end up with:

"""
Word Counter

Given an body of text, return a hash table of the frequency of each
word.
"""

def word_count(sentence):
    """
    Word Counter

    Given an body of text, return a hash table of the frequency of
    each word.

    ..  warnings::

        - Capital and lower case versions of the same word should be counted

    as the same word.

        - Remove punctuations from all words.

    ..  note::

    Where N is the number of characters in the string.

        - Time: O(N)

        - Space: O(N)

    :Example:

    >>> word_count('The cat and the hat.')
    {'the': 2, 'cat': 1, 'and': 1, 'hat': 1}
    >>> word_count('As soon as possible.')
    {'as': 2, 'soon': 1, 'possible': 1}
    >>> word_count("It's a man, it's a plane, it's superman!")
    {'its': 3, 'a': 2, 'man': 1, 'plane': 1, 'superman': 1}

    :param sentence: Input string
    :type sentence: str

    :return: Returns hash-table of frequence of each word in input
    :rtype: dict
    """

    translate = sentence.maketrans({char: None for char in "'.,:*!"})
    cleaned_words = sentence.lower().translate(translate).split()
    word_counter = {}
    for word in cleaned_words:
        if word in word_counter:
            word_counter[word] += 1
        else:
            word_counter[word] = 1
    return word_counter

You can also make use of collections.counter which has the same complexity as your current code. However, it also provides a few extra features on the resulting counter object, such as most_common.

The referenced links above are for python-2.7; however all the modules/packages are available in python 3.x


Python RPC Design Pattern - is bidrectional coupling a good idea? I want to build a barebones system according to the following spec:
Given a setup of n computers, if the ith computer receives an operation to update a given key-value pair, it should perform the update, and propagate it to all other nodes. I'd like communication between nodes to be done with RPC.
I have the following runnable code that works fine:
import aiomas

class RpcCall:
    def __init__(self, port, method):
        self.port = port
        self.method = method

    async def __call__(self, *args, **kwargs):
        rpc_con = await aiomas.rpc.open_connection(("localhost", self.port))
        rep = await getattr(rpc_con.remote, "redirect")(*args, **kwargs, method_name=self.method)
        await rpc_con.close()
        return rep

class Node:
    def __init__(self, port, neb_ports):
        self.server = None
        self.port = port
        self.table = {}
        self.neb_ports = neb_ports

    def start(self):
        self.server = aiomas.run(aiomas.rpc.start_server(("localhost", self.port), Server(self)))

    def close(self):
        self.server.close()
        aiomas.run(self.server.wait_closed())

    async def update(self, key, value, replicate=True):
        self.table[key] = value
        if replicate:
            for neb in self.neb_ports:
                await self.replicate(neb, "update", key=key, value=value, replicate=False)

    async def replicate(self, node, method_name, *args, **kwargs):
        rpc_call = RpcCall(node, method_name)
        await rpc_call(*args, **kwargs)

class Server:
    router = aiomas.rpc.Service()

    def __init__(self, node: Node):
        self.node = node

    @aiomas.expose
    async def redirect(self, method_name, *args, **kwargs):
        func = getattr(self.node, method_name)
        await func(*args, **kwargs)

if __name__ == "__main__":
    n1 = Node(5555, [5556])
    n2 = Node(5556, [5555])
    n1.start()
    n2.start()

    aiomas.run(n1.update("foo", "bar"))

    print(n1.table)
    print(n2.table)

As the output should show, the table is replicated onto both nodes, ensuring there's no data loss in case one node dies.
I'm looking for a review specifically on the design pattern used in the above.
I've coupled the Node and Server classes so that whenever the Server receives an RPC call, it delegates it back to the Node, which then performs the operation on the underlying table
Good idea/bad idea?

On the coding side, every Node has an attribute Server and the Server has a reference to the Node it belongs to. Node calls Server's methods, and Server reads Node's attributes, so they currently are inseparable classes. I would suggest refactoring this, and - personally - I would just merge the two classes.
I'm also not sure why RpcCall needs to be a callable class, other than for the sake of enforcing OOP. It looks like a simple function (or another method in Node) would do just as well. Then again, maybe your real scenario needs it to be a separate class.
for neb in self.neb_ports:
    await self.replicate(...)

This line defeats the purpose of asyncronous IO, because you are waiting for each call to finish before starting the next one. You could look into Asyncio.gather to start and await multiple such calls in parallel instead of sequentially.

Regarding reliability, you - unfortunately - have none. If one node fails, it will bring peer-nodes down at the next attempt to sync the key-value store. The reason is that you are awaiting a function that will timeout and raise and Exception if a connection can't be established. You are not handling this exception anywhere, so the calling node will halt. If keys are updated often enough, your entire cluster will die due to this.
If a connection can be established, I'm not sure what will happen if either node dies. I briefly searched aiomas, but couldn't find related documentation. My guess is that the call will just hang indefinitely. This is potentially worse than a clean crash because your node will be leaky and silently suffer a death by a thousand cuts. Log messagees (if any) will likely point you into the wrong direction, making this problem hard to debug.
On the point of fault-tolerant because "there is no data loss because nodes replicate preemptively" it really isn't just that simple.
The sore point is the hierarchy among nodes, or rather the lack thereof. If the network for one node dies temporarily, it won't receive any further updates. To the node, the faulty network and not getting state changes look alike, so it will continue running happily. To the other nodes of the cluster it looks like the node died, and - assuming you add exception handling - they will continue to change state jointly. After the network issue is resolved, the lost node will reappear in the cluster and continue serving happily. However, it is now out of sync and will serve potentially outdated key-value pairs or report missing values for new ones that were set during the network outage.
Assume this happens to multiple nodes; you'll end up with a heterogenious cluster and - because you lack hierarchy among your nodes - it is impossible to say what the correct state should be. Currently, you can't differentiate the order in which state-changes occurred, so rebuilding the state is ambiguous. You will need to define merging and conflict resolution mechanisms to re-establish synced state.
You may also wish to establish a heartbeat for the cluster so that a node can discover connection issues. How it should handle them is context-dependent, but an easy first idea is for the node to simply suicide.
Instead of creating a homebrew design-pattern for this, it may be easier to follow an established consensus method such as RAFT or PAXOS. This will take care of a lot of edge cases and may make your life considerably easier.


Given N, generate sequence of random numbers from 0 to N - 1 with no repetitions Problem statement:
Given an integer n, write a function to return an array of size n, containing each of the numbers from 0 to n-1 in a random order. The numbers may not repeat and each number must show up exactly once.

Solution # 1:
Generate an ordered array then shuffle it

private static int[] Shuffle(int n)
{
    var a = Enumerable.Range(0, n).ToArray();
    var random = new Random();
    for (int i = 0; i < a.Length; i++) {
        var j = random.Next(0, i);
        Swap(a, i, j);
    }
    return a;
}

private static void Swap(int[] a, int i, int j)
{
    var temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}

Solution # 2:
Generate empty array and add items in random order

private static int[] Shuffle(int n) {
    var a = new int[n];
    var random = new Random();
    for (int i = 0; i < a.Length; i++) {
        var j = random.Next(0, i);
        Swap(a, i, j);
    }
    return a;
}

private static void Swap(int[] a, int i, int j) {
    var temp = i;
    a[i] = a[j];
    a[j] = temp;
}

I'm not fully persuaded about the randomness of solution # 2. Are there better ways of achieving the solution? I'm assuming that whatever approach is taken the solution can only be produced in linear time. Is this conclusion correct?

You can use the inside out version of the Fisher-Yates shuffle

In C# it would look like:

private static int[] Shuffle(int n)
{
    var random = new Random();
    var result = new int[n];
    for (var i = 0; i < n; i ++)
    {
        var j = random.Next(0, i + 1);
        if (i != j)
        {
            result[i] = result[j];
        }
        result[j] = i;
    }
    return result;
}

It's good because you create and shuffle your array at the same time using a well known shuffle.

You'd want to reuse the same Random instance though.


UserDefaults - defaults...? I made this generic class which helps me reading values from user defaults. Besides it abusing several UserDefaults... what do you see? Can I make some instances share a reference?

class DefaultValue<V> {
    var userDefaults = UserDefaults()
    let name : String
    let defValue : V

    init(name: String, defValue: V) {
        self.name = name
        self.defValue = defValue
    }

    func get() -> V {
        if userDefaults.object(forKey: name) == nil {
            return defValue
        }
        switch defValue {
        case is Int:
            return userDefaults.integer(forKey: name) as! V
        case is Bool:
            return userDefaults.bool(forKey: name) as! V
        case is String:
            return userDefaults.string(forKey: name) as! V
        default:
            return defValue
        }
    }

    func set(value: V) {
        userDefaults.set(value, forKey: name)
    }

    func reset() {
        userDefaults.set(defValue, forKey: name)
    }
}

Usage:

class MyDefaults {
    let LOGGED_IN = DefaultValue<Bool> (name: "logged_in", defValue: false)
    let USERNAME = DefaultValue<String> (name: "username", defValue: "")
}

var settings = MyDefaults()
if settings.LOGGED_IN.get() {
    settings.LOGGED_IN.set(value: true)
} else {
    settings.LOGGED_IN.reset()
}

The forced casts as! V in the get() method might seem safe at first
sight, since you do some type-checking before. But they are not:
If a default value for some key exists, but is of the wrong type then
your program can crash. This can for example happen if you change the
type of some default value between program releases. You can easily
reproduce the problem by setting the default value to an incompatible
type before retrieving it with your class:

UserDefaults.standard.set([1, 2, 3], forKey: "username")

class MyDefaults {
    let USERNAME = DefaultValue<String> (name: "username", defValue: "Joe")
}

print(MyDefaults.USERNAME.get())

which crashes at

return userDefaults.string(forKey: name) as! V
// Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

This can be avoided with optional casting as? V, and then the
entire get() method simplifies to

func get() -> V {
    return userDefaults.object(forKey: name) as? V ?? defValue
}

As a bonus, the code now works not only with integers, booleans and
strings, but with all types (provided that they are “UserDefaults compatible”).

I do not see a reason to create separate UserDefaults instances,
you can share the standard instance:

let userDefaults = UserDefaults.standard

The reset() method could simply remove the value instead of setting
the default value:

func reset() {
    userDefaults.removeObject(forKey: name)
}

A possible advantage is that you can retrieve it with a different
default value later.

I would use “default” as argument label in the init method:

init(name: String, default defValue: V) {
    self.name = name
    self.defValue = defValue
}

That looks nicer when called

let USERNAME = DefaultValue<String> (name: "username", default: "")

and also mimics the subscript(_:default:) of Swift dictionaries.

The set() method should have an empty argument label

func set(_ value: V) {
    userDefaults.set(value, forKey: name)
}

like, for example, set(_:forKey:).

If your intention of class MyDefaults is to avoid global variables
and to provide a “namespace”: This can also be achieved with a
case-less enum:

enum MyDefaults {
    static let USERNAME = DefaultValue<String>(name: "username", default: "")
}

MyDefaults.USERNAME.set("elcuco")
print(MyDefaults.USERNAME.get())

so that no instances have to be created.

Naming: According to the Swift API Design Guidelines:

  Names of types and protocols are UpperCamelCase. Everything else is lowerCamelCase

so it should be

enum MyDefaults {
    static let loggedIn = DefaultValue<Bool> (name: "logged_in", default: false)
    static let userName = DefaultValue<String>(name: "username", default: "")
}

instead of LOGGED_IN and USERNAME.


Lights on: playing with buttons in Javascript First play with the game a little bit, and it is quite fun (a little hard but very satisfying when you win, be sure to put it full page):

<!DOCTYPE html5>

  <title>Lights on</title>

Clicking a button inverts it and its neightbours.
You win when you switch on all the lights.

  <button style="height:150px;width:150px" id=1 onclick="switch_with_neightbors(1)">0</button>
  <button style="height:150px;width:150px" id=2 onclick="switch_with_neightbors(2)">1</button>
  <button style="height:150px;width:150px" id=3 onclick="switch_with_neightbors(3)">0</button>

  <button style="height:150px;width:150px" id=4 onclick="switch_with_neightbors(4)">1</button>
  <button style="height:150px;width:150px" id=5 onclick="switch_with_neightbors(5)">1</button>
  <button style="height:150px;width:150px" id=6 onclick="switch_with_neightbors(6)">1</button>

  <button style="height:150px;width:150px" id=7 onclick="switch_with_neightbors(7)">1</button>
  <button style="height:150px;width:150px" id=8 onclick="switch_with_neightbors(8)">1</button>
  <button style="height:150px;width:150px" id=9 onclick="switch_with_neightbors(9)">0</button>

Ok, now the bad news:

I put HTML and JavaScript together. Would separating them improve readability?
I generate 9 buttons by hand, and I copy-paste the size for each one. Can I avoid so much repetition?
I am confused by the looping constructs of JavaScript. Is my use of the for .. in sensible?
I put the neighbours hash inside a function. Is this standard practice? Is this weird?
I cast variables to different types all the time. Can you help me spot unnecessary conversions?
Is my code modular enough?

I'll just start by looking at what you have, and then I'll get to your questions. (Edit: Seems I'm retreading a lot of what SirPython already covered. Didn't see that answer before I posted. Apologies for boring the reader, and no plagiarism of SirPython intended. Don't mess with a knighted snake!)

The HTML

The doctype for HTML5 is just <!DOCTYPE html> - there's no 5 in the the doctype declaration.
You're missing a <body> opening tag.
I'd recommend you consistently use quotes around your attribute values. Right now you have id=3 with no quotes. It's perfectly valid to skip them (provided the attribute value doesn't have spaces in it), but more often than not, you end up needing the quotes around other values anyway, so for the sake of consistency: Always use quotes.
I'm not keen on using p elements for the button rows. Semantically speaking they're not really paragraphs, per se. I'd use divs, since they're semantically neutral and more geared toward pure layout concerns.
Avoid style attributes in the HTML. Especially here, as it all repeats verbatim for each button. I'd suggest putting CSS in a style element in the head:

<style>
  button {
    width: 150px;
    height: 150px;
  }
</style>

That'll take care of all of them.
Avoid onclick attributes. They're sooo last century. But seriously, it's generally considered better form to use addEventListener to attach event handlers via JavaScript, rather than having little bits of JS scattered all over the HTML.

If you do use onclick know that you can pass this to the function, i.e. onclick="switch_with_neighbors(this)". In an attribute, this refers to the button itself, so you don't have to go find it again in the function (or repeat the id attribute's value in the onclick attribute).

The JavaScript

The JS naming convention is camelCase, not snake_case. Right now, you end up having to mix the two, since the DOM already uses camelCase (e.g. getElementById) so consistency suffers.
You have a typo that seems to have been repeated (I'm guessing your editor auto-completed it for you): "neightbors". It's also in the HTML.
You have a couple of unintentionally global variables. If you neglect the var keyword, an variable assignment/initialization like foo = bar is interpreted as window.foo = bar, i.e. the variable becomes a property on the window object (which in browser JavaScript means it's a global variable).

The ones I spotted were button in invert_text() and nears in switch_with_neightbors().
The way you track and set a button's state is somewhat brittle, relying on its innerHTML, some type conversion, and manually changing its background color. I'd recommend using classes instead. You can check the presence of a class with someElement.classList.contains("someClass"), and use classList.add/classList.remove or simply classList.toggle to toggle the class on and off.

So for instance you could have a lit class, or more conventionally (though less domain-specific) an active class. The class would define background color, so adding/removing it from the classlist would cause all the effects you want.

Edit: I've added an example at the end of the answer.
There's are a few too many hardcoded bits in the code for my liking. Several hardcoded 9s, and of course the table of neighbors. I'd extract the 9 into a "constant", just so it's not a magic number floating around. As for the neighbors-table, you can work that out at runtime. You don't even need element IDs; a getElementsByTagName or querySelectorAll will return the elements in their document order. So you'll have an array (well, a NodeList instance but for our purposes it's the same) and with a little bit of index arithmetic you can work out the neighbors. It's more code though, so I maybe wouldn't bother too much. Still, the neighbors table just irks me a little.
Speaking of the neightbors (sic) table, note that object properties are always considered strings (more on that later), so using a number literal as a property name is suspect, e.g. { 3: someValue }. In fact, I wouldn't be surprised if some browsers choke on it, since it seems to be bordering on a syntax error (not that I know the ECMA spec by heart).

Basically, you can access object properties with dot notation - i.e. obj.property - or with subscripting like an array - i.e. obj[property]. The first option becomes impossible if you just have a number as the property name, since obj.3 is a syntax error.

It's often better for property names to follow the same rules as variable names, i.e. can't start with a number, have spaces, or just be a number. So e.g. button3 would be nicer.
For bonus points, shove everything inside an IIFE (immediately-invoked function expression):

(function () {
  // all your code
})();

This causes all of your functions to be defined in a local scope, rather than the global window scope. Thus you avoid polluting the global scope (i.e. accidentally overwriting an existing function, or risking other code doing that to you).

One gotcha is that you can't use onclick anymore, since you'd be referring to a function that's no longer in the global scope. There are ways to get around this of course, but again I'd rather not use onclick anyway.
You've got a stray console.log in there. It's not a big deal, but it's the sort of debug cruft that should be removed before you "ship" the code.

Questions

  I put HTML and JavaScript together. Would separating them improve readability?

Yes and no. For larger projects, I'd say use separate files. But for a little experiment like this, it's fine. I'd still avoid the onclick attributes, though, in favor of a cleaner separation.

Note that you can also put your script tag at the end of the body element, in which case you won't need to listen for the DOMContentLoaded event, since all the above will of course have been loaded when the script's evaluated.

  I generate 9 buttons by hand, and I copy-paste the size for each one. Can I avoid so much repetition?

For the button size, see the bit about CSS above. As for creating the buttons, you can do that in JS without too much hassle. And if you do, you can also stick the elements in an array, so you don't need to go through the DOM to find them again. The basic principle would be something like:

var buttons = [];

for(var i = 0; i < ROW_COUNT; i++) {
  var row = document.createElement("div");
  document.body.appendChild(row);

  for(var j = 0; j < COLUMN_COUNT; j++) {
    var button = document.createElement("button");
    button.addEventListener("click", handleClick, false);
    row.appendChild(button);
    buttons.push(button);
  }
}

Maybe you'll want to use a 2D array for the buttons, so it matches the layout (you'll have less index arithmetic to deal with when finding neighbors), but either thing can work.

  I am confused by the looping constructs of JavaScript. Is my use of the for .. in sensible?

Yes, you seem to using it correctly. Edit: Actually, no. I wasn't paying close enough attention. If you had been iterating the neightbors object it'd be cool (and that's what I thought you were doing), but you're iterating the nears array, which is not a job for for..in.

It's common mistake to use the for..in loop for arrays, since other languages use their for..in that way. But JS's for..in is designed to iterate object properties, specifically; not array elements. It'll (seem to) work, since array elements are properties on the array, and thus get iterated. But your intention is not to iterate them as though they were properties; you want to treat them as array elements.

So: Iterating an object? Use for..in. Iterating an array? Use a regular for (or the forEach function).

  I put the neighbours hash inside a function. Is this standard practice? Is this weird?

Well, it doesn't change, so it might as well be outside the function. Any JavaScript runtime from the last decade will no doubt optimize that away, though, so it's not like it's a performance issue or anything (even if it wasn't optimized away, it still wouldn't make a dent in performance). But from a structural standpoint, it's a little iffy to have an essentially constant value be a local variable that's declared and defined on each function invocation.

  I cast variables to different types all the time. Can you help me spot unnecessary conversions?

Yes: All of 'em look unnecessary :)

JS is very loose when it comes to type (sometimes it's just plain weird, but that's another story). So getElementById(3) and getElementById("3") are equivalent. And in the case of your neightbors table, there's a twist: As mentioned, all JavaScript property names are strings internally, so when you say neightbors[parseInt(current, 10)]; you're taking a string, turning it into a number, and then JS turns it back into a string again to do the lookup in the neightbors object's properties. So you're doing the opposite of what's "natural" - and yet it still works :)

Similarly, all DOM attribute values are strings by default (since HTML is all text). In your case you've used single digits as IDs (note: as with object properties it's better to assume that IDs should work as plain variable names and follow those rules), but they're rendered as strings. Funny thing is that a string that's just a plain number will be silently coerced to a number when needed. So for instance, an array lookup like [1, 2, 3]["1"] will return 2 just fine, even though array indices are numbers. And similarly, as you've already seen, object lookups will coerce stuff to strings: ({ 42: "foo" })[42].

The most common source of type-confusion is probably mixing strings and numbers. For instance, 2 + "2" yields the string "22", not the number 4. So in such a case, it's a good idea to explicitly cast/convert your variables - either to achieve to desired outcome (e.g. numeric addition), or just to clarify your intention (e.g. yes, I do want string concatenation).

  Is my code modular enough?

It's nicely divided into functions, but you do have some cross-coupling with the DOM elements (i.e. onclick) and some magic numbers/hardcoding.

Don't know if I'd call it "modular" because there's really only one "module": The game. I'd rather ask if it's "well-factored", and to that I'd answer, yeah, it's not bad at all. But of course, I have also written a huge review (see all of the above) for you to chew on :)

Edit: As requested, here's a simple one-button example of using a class to toggle and keep state:

document.querySelector("button").addEventListener("click", function () {
  // Toggle the "active" class on click
  this.classList.toggle("active");

  // An example of how to test the button's state (check the console)
  if(this.classList.contains("active")) {
    console.log("Button is now on");
  } else {
    console.log("Button is now off");
  }
}, false);
/* base styling */
button {
  width: 100px;
  height: 100px;
  background-color: red;
  outline: none; /* hides the "halo" that otherwise appears when you click the button */
}

/* active/lit styling */
button.active {
  background-color: green;
}
<button></button>


Integer Partition using an iterator I tried implementing Integer Partition (enumerating all possible sets of whole numbers whose sum is a given integer).

Looking at @rolfl's answer, I reasoned that with a stack data structure, we shouldn't need to use recursion, since recursion implicitly stores state in the call stack.  I also tried to address @JeffVanzella's criticism about separation of concerns by converting the class into an iterator.

My solution ended up being a bit more monstrous than I had anticipated.  It looks nothing like the elegant original, and runs more slowly too.  Therefore, I suspect that a better iterative solution is possible.

import java.util.Iterator;

public class Partition implements Iterator<String> {
    /**
     * Fixed-capacity stack of ints.  As used in Partition.next(), the
     * invariant is that elements towards the top of the stack are never
     * larger than elements underneath.  (In other words, the array
     * elements are nonincreasing.
     */
    private static class IntStack {
        private int[] data;
        private int size;

        IntStack(int capacity) {
            this.data = new int[capacity];
            this.size = 0;
        }

        public void push(int datum) {
            this.data[this.size++] = datum;
        }

        public int pop() {
            return this.data[--this.size];
        }

        public boolean isEmpty() {
            return this.size == 0;
        }

        /**
         * Returns the elements as a space-delimited string.
         */
        public String toString() {
            // toString() of an empty stack is never used in practice...
            if (this.isEmpty()) return "";

            StringBuilder sb = new StringBuilder(String.valueOf(this.data[0]));
            for (int i = 1; i < this.size; i++) {
                sb.append(' ').append(String.valueOf(this.data[i]));
            }
            return sb.toString();
        }
    }

    //////////////////////////////////////////////////////////////////////

    private IntStack stack;

    public Partition(int n) {
        if (n <= 0) throw new IllegalArgumentException();
        stack = new IntStack(n);
        stack.push(n);
    }

    @Override
    public boolean hasNext() {
        return !stack.isEmpty();
    }

    @Override
    public String next() {
        String retval = stack.toString();

        int top;
        int ones = 0;

        // Count the ones at the top of the stack. Stop at "top", which is the
        // next element other than a 1.
        while (1 == (top = stack.pop())) {
            if (stack.isEmpty()) {
                // n has been completely partitioned into n ones.  All done!
                return retval;
            }
            ones++;
        }

        // Transfer 1 from top to ones, then write out the remainder in as few
        // numbers as possible, observing the stack invariant that entries
        // must be nonincreasing.
        stack.push(--top);
        for (ones++; ones > 0; ones -= top) {
            stack.push(top < ones ? top : ones);
        }
        return retval;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }

    public static void main(String[] args)
    {
        int n = Integer.parseInt(args[0]);
        Partition p = new Partition(n);
        while (p.hasNext()) {
            System.out.println(p.next());
        }
    }
}

I am not sure how to 'review' your code in this case.... I have a sense of 'competition' here, and the moment performance enters the equation, there are things I just know are going to be slower, but I cannot always explain why.....

I think often times it simply comes down to primitives vs. Object creation.... whenever that happens things slow down.

I have put together a 'competing' solution, and it uses tricks I have learned over the years... tricks I feel, for the most part, lead to 'fast' code. I have been accused of 'premature optimization' when I do these things, but, it tends to work for me.... ;-)

printing Strings is never going to be a good measure of performance, so I have taken three solutions: the recursive solution I suggested in the earlier post. Your solution using the iterator, and then a 'competing' iterator performance.

So, in my benchmarks, this iterative process is about 5 times faster than yours.... (excluding the System.out.println()):

here are my results (times in milliseconds on my machine):

200_Success=2045.091 rolflIter=446.846=rolflRecur 2046.462011
200_Success=1737.469 rolflIter=573.900=rolflRecur 1521.951070
200_Success=1814.468 rolflIter=385.520=rolflRecur 1499.896568
200_Success=1714.592 rolflIter=333.105=rolflRecur 1372.042103
200_Success=1799.969 rolflIter=383.033=rolflRecur 1520.779467
200_Success=1676.415 rolflIter=336.651=rolflRecur 1474.669545
200_Success=1978.581 rolflIter=407.804=rolflRecur 1417.124248
200_Success=1665.783 rolflIter=343.939=rolflRecur 1375.178203
200_Success=1654.083 rolflIter=331.607=rolflRecur 1369.912767
200_Success=1654.958 rolflIter=339.234=rolflRecur 1369.170302

Edit:
New results ... note, 200_success is also running faster here....
Hate performance variances ... probably a Windows/Intel CPU frequency thing.

200_Success=1463.484 rolflIter=624.754 rolflRecur=1777.548864
200_Success=1304.401 rolflIter=302.086 rolflRecur=1492.951479
200_Success=1577.132 rolflIter=367.537 rolflRecur=1485.176134
200_Success=1230.959 rolflIter=266.068 rolflRecur=1389.742206
200_Success=1230.445 rolflIter=269.587 rolflRecur=1382.473980
200_Success=1220.637 rolflIter=269.352 rolflRecur=1376.292369
200_Success=1204.206 rolflIter=266.920 rolflRecur=1369.920239
200_Success=1201.280 rolflIter=264.481 rolflRecur=1365.711999
200_Success=1204.419 rolflIter=262.047 rolflRecur=1368.854637
200_Success=1251.656 rolflIter=264.030 rolflRecur=1416.935596

Main class:

package comp;

import java.util.Iterator;

public class RunParts {

    private static int charsIn(Iterator<String> iter) {
        int chars = 0;
        while (iter.hasNext()) {
            chars += iter.next().length();
        }
        return chars;
    }

    public static void main(String[] args) {
        final int target = Integer.parseInt(args[0]);
        long[] nanos = new long[3];
        int[] charlen = new int[3];
        for (int i = 0; i < 10; i++) {
            System.gc();
            nanos[0] = System.nanoTime();
            charlen[0] = charsIn(new Partition(target));
            nanos[0] = System.nanoTime() - nanos[0];

            System.gc();
            nanos[1] = System.nanoTime();
            charlen[1] = charsIn(new PartitionRLIter(target));
            nanos[1] = System.nanoTime() - nanos[1];

            System.gc();
            nanos[2] = System.nanoTime();
            charlen[2] = PartitionRLRecur.partitionRL(target);
            nanos[2] = System.nanoTime() - nanos[2];

            System.out.printf("200_Success=%.3f rolflIter=%.3f rolflRecur=%3f\n",
                    nanos[0] / 1000000.0, nanos[1] / 1000000.0, nanos[2] / 1000000.0);
        }

    }

}

Your solution is above (I have left it called 'Partition').

Then my iterative solution is...

EDIT:
I have edited my solution to add comments. As I was adding the comments I realized that a lot of the logic in the advance() method was related to setup of the system.
I have moved the setup to the constructor, and by verifying a couple of things, I am now able to guarantee a couple of behavioral advantages that mean I don't need a few of the loops in the system. I have updated my results now as well.

package comp;

import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;

public class PartitionRLIter implements Iterator<String> {

    private final int[] stack;
    private final int[] outpos;
    private final StringBuilder outstring;
    private final int limit;
    private boolean hasnext = true;
    private int spos = 0;

    public PartitionRLIter(int n) {
        if (n <= 0) throw new IllegalArgumentException();
        limit = n;
        stack = new int[limit];
        outpos = new int[limit];
        // NOTE THAT THE CONSTRUCTOR NOW MANUALLY INITIALIZES THE SYSTEM
        outstring = new StringBuilder(limit * 2); // worst case is "1 1 1 1 1 ...";
        Arrays.fill(stack, 1);
        for (int i = 0; i < limit; i++) {
            outpos[i] = outstring.length();
            outstring.append("1 ");
        }
        hasnext = true;
        spos = limit - 1;
    }

    @Override
    public boolean hasNext() {
        return hasnext;
    }

    @Override
    public String next() {
        if (!hasnext)
            throw new NoSuchElementException();

        try {
            return outstring.substring(0, outstring.length() - 1);
        } finally {
            hasnext = advance();
        }
    }

    private final boolean advance() {
        // advance() keeps four 'stack-like' variables in sync
        // advance() will only ever be called when the current system has a valid answer
        //
        // **stack** contains the digits that get summed... It is the 'real stack'. The constructor initializes it to all 1's.
        //
        // **spos** is our depth in the stack.
        //
        // the **outstring** is a StringBuilder that is kept in sync with the actual stack...
        //     reusing the StringBuilder makes it much faster... but we need to manage it like a stack.
        //     when you go deeper in the stack, the outstring has values added to it,
        //     when you come back up, the outstring is truncated to remove unneeded characters.
        //     very much like push and pop operations (except at the end of the string, not the front)
        //
        // the **outpos** is the array of integer positions in the outstring StringBuffer that
        //     keeps track of where the outstring should be truncated at each level.
        //     this is what allows working push/pop on the outstring.
        //

        // back up..... the stack, we always know we are already at the limit.
        // pop the value off (keep sum in sync).
        int sum = limit - stack[spos];
        if (--spos < 0) {
            // we ran out of things to do, there's no more possibilities.
            return false;
        }

        // on the previous level, we increment....
        // we can never overflow the previous level because
        // of the way the math works (we would not have a next level if we can't increment this one).
        stack[spos] ++;
        sum++;

        // pop the previous value(s) off the stack representation.
        // outpos[spos] contains the character position in the output representing
        // our current depth.
        outstring.setLength(outpos[spos]);

        // check to see whether adding a new level of depth will work.....
        // the new level will have the same value as the stack's current value...
        while (sum + stack[spos] <= limit) {
            // yes, the new level will work.
            // update our string stack, sum, and record the character position of the outstring.
            outstring.append(stack[spos]).append(" ");
            sum+= stack[spos];
            stack[spos + 1] = stack[spos];
            spos++;
            outpos[spos]=outstring.length();
        }

        // take the new depth and increment it (if needed) to the limit.
        stack[spos] += limit - sum;
        outstring.append(stack[spos]).append(" ");
        return true;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }
}

Finally, my Recursive solution is (note, it has been modified to return the string length, not the string itself):

package comp;

public class PartitionRLRecur {

    public static int partitionRL(final int n)
    {
        return recursivePartition(n, 1, new int[n], 0);
    }

    private static int recursivePartition(final int target, final int from, final int[] stack, final int stacksize)
    {
        if(target == 0) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < stacksize; i++) {
                sb.append(stack[i]).append(" ");
            }
//            System.out.println(sb.toString());
//          );
            return sb.toString().length();
        }
        int sz = 0;
        for(int i = from; i <= target; i++) {
            stack[stacksize] = i;
            sz += recursivePartition(target-i, i, stack, stacksize + 1);
        }
        return sz;
    }

}


Bash script to capture error message and change exit status I'm working with the Perforce command line client.                                                                                I want to check for the case when a user tries to unshelve an unsubmitted changelist that has a valid changelist number, but has no shelved files. In this case the p4 unshelve command will still have an exit status of 0, but it will print an error message to stderr.

I'm fairly inexperienced with bash scripts, but I did run my code through shellcheck.net to find any obvious errors.

In a lot of places I think this script could be more concise or robust, but I don't know exactly what I should be changing.

Any help is greatly appreciated.

#!/bin/bash

p4 unshelve -f -s "$1"  &> tmp_file

# capture the exit status of the call to p4 unshelve
if [ $? -eq 0 ]
then
    flag0=0
else
    flag0=1
fi

std_err_output="$(cat tmp_file)"
error_message="No such file(s)."

# even if the exit status is 0, still check that the error message was not thrown.
if [ "$std_err_output" = "$error_message" ]
then
   flag1=1
else
   flag1=0
fi

rm tmp_file

exit_status="expr $flag0 | $flag1"

exit "$($exit_status)"

Pretty nice job for someone new to bash.
I have a couple of tips though.

Instead of this:

# capture the exit status of the call to p4 unshelve
if [ $? -eq 0 ]
then
    flag0=0
else
    flag0=1
fi

You can write simply:

flag0=$?

It's not exactly the same, because the error code might not be 1, but we can make it work with this lazy way too, see below.

Similar to earlier, instead of this:

if [ "$std_err_output" = "$error_message" ]
then
   flag1=1
else
   flag1=0
fi

You can do simpler:

[ "$std_err_output" = "$error_message" ]
flag1=$?

Similarly, instead of this:

exit_status="expr $flag0 | $flag1"

exit "$($exit_status)"

You can benefit from the fact that the exit code of the script will be the exit code of the last command. So you can simply write:

[ $flag0 = 0 ] && [ $flag1 = 0 ]

Lastly, I suggest to move the rm tmp_file higher, to get it done as soon as you no longer need that file. No need to keep it around any longer than necessary.


Should Golang interface be shared among different packages of an application? I'm developing a Go application that has lots of packages.
Many of the packages use the same type from a 3rd party library.
Should an interface be defined for the type in each package, and let the interfaces only contain the methods that are used by the package?
Or, we should define a single interface for the whole application, and let the interface contain the union of all the methods that are used throughout the application?
At official Golang wiki, there's a statement

    Go interfaces generally belong in the package that uses values of the interface type, not the package that implements those values.

But does the package means the one that actually uses the type or the root package of the project?
Here's a simplified example:

package subnet
type netOpsClient interface {
    Subnets(ctx context.Context, options map[string]string) ([]string, error)
}

type PrimaryNetFinder struct {
    netOpsClient netOpsClient
}

func (p *PrimaryNetFinder) Find(ctx context.Context) ([]string, error) {
    subnets, err := p.netOpsClient.Subnets(ctx, map[string]string{
        "level": "50",
    })
    //...
}

package loader
type netOpsClient interface {
    Subnets(ctx context.Context, options map[string]string) ([]string, error)
    SubnetGet(ctx context.Context, id string) (netops.Subnet, error)
}
type RulesLoader struct {
    netOpsClient netOpsClient
    policyStore policyStore
}
func (r *RulesLoader) LoadRules(ctx context.Context) error {
    //...
    subnets, err := r.netOpsClient.Subnets(ctx, map[string]string{
        "level": level,
        "site": "ne",
    })
    //...
    subnet, err := r.netOpsClient.SubnetGet(ctx, subnetId)
    //...
    policies, err := policyStore.Policies(subnet.cidr)
    //...
}

You can see both PrimaryNetFinder and RulesLoader store a field of type netOpsClient, which is an interface defined in the package. And a type from a 3-party NetOpsClient implements the interface.
If many packages in the project have a reference to the type, should each package define a similar interface like above? Or, should I define a single interface, and let all the packages share the same interface like below?

package netops
type NetOpsClient interface {
    Subnets(ctx context.Context, options map[string]string) ([]string, error)
    SubnetGet(ctx context.Context, id string) (netops.Subnet, error)
    // ...
}

Personally I would define it in each package that uses it. It would only be a small amount of duplication but has many advantages:

It keeps the package self contained.
You mentioned that not all packages use the same method so it stops the interface getting very large.
If not every package uses each method it makes it explicit which method a package does use.


C# Random Password Generation So I have a method that, after validation, generates a random password based on the length and characters provided. The UI uses check boxes to select using between lowercase and/or uppercase letters, numbers and special characters to populate the characters parameter. as well as the length of the password and the spacing between each character used (I.E. if character spacing is set to '10', the letter 'A', for example, can only be used again after another 10 unique characters are used first):

The Generator Method:

    private string PasswordGeneration(string characters, int length)
    {
        var random = Factory.Random(); //Generates new Random() from Factory class.
        var availableCharacters = characters; //Preps the available characters with all characters passed.
        var output = string.Empty;
        var rule = ValidateRule(characters.Length); //Sets character rule to length of parameter "characters" if the unique character spacing is set higher than the number of available characters to use.
        for (var position = 0; position < length; position++) //loop until we've met the password's desired length.
        {
            if (rule != 0 && (characters.Length - availableCharacters.Length == rule)) //if a character rule is set & if we've met the criteria of the number of unique characters asked for...
            {
                availableCharacters = characters.Where(c => !output.Substring((position - rule) + 1, rule - 1).Contains(c)).Aggregate(availableCharacters, (current, c) => current + (current.Contains(c) ? string.Empty : c.ToString()));
                //...we add back all characters for usage other than the last n characters used dictated by the unique character rule.
            }
            var character = availableCharacters[random.Next(availableCharacters.Length)]; //Grabs a random character from availableCharacters.
            availableCharacters = rule == 0 ? availableCharacters : availableCharacters.Replace(character.ToString(), string.Empty); //If a character rule is set, we remove the currently used character from availableCharacters.
            output += character; //Append "character" to output.
        }
        return output;
    }

The 'ValidateRule()' Method:

        private int ValidateRule(int length) =>
        length - _settings.IdenticalSpacing > 0
            ? _settings.IdenticalSpacing
            : length;

And for readability with what's happening with the LINQ expression within the if statement:

foreach(var c in characters)//...we iterate through the original set of characters...
{
    if(output.Substring((position - rule) + 1, rule -1).Contains(c) == false)//...and check to see if the a specific range contains each character. If the range doesn't contain the current character...
    {
        foreach(var availableCharacter in availableCharacters)//...we iterate through our available characters to see if it doesn't already contains the current character...
        {
            if(!Equals(availableCharacter, c))
            {
                availableCharacters += c; //...if not, we make the character available for use again.
            }
        }
    }
}

As stated before, the characters and password length parameters are all validated before being passed to PasswordGeneration(), so I didn't add any null checking or checks for bad inputs other than for the character spacing rule. While everything works perfectly fine with no errors, I feel as if the code looks messy and of course a bit hard to read. I can't help but think there's a much more simple approach without a bunch of loops and conditions or long LINQ expressions. However, I would love to hear some feedback on what you all think and of course, how I can improve this.

There are lots of ways to improve this hard-to-read code but all of them are unimportant compared to the fact that this is massively insecure against common attacks.  You are implementing a component of a security system; you need to build a threat model and understand what you are doing.  Implementing a security system is not a beginner task!

An important rule to follow is never use System.Random for a security purpose.

A random number generator needs to be genuinely unpredictable for it to be used in a security system that depends on unpredictability. System.Random is not truly random, and nor is it crypto strength pseudo random.

Why does this matter? Because an attacker who knows anything about the system used to generate the passwords can make good guesses about what passwords it will generate, much better than chance. How does the attacker get information about the system? A generated password leaks information about the state of the system.

That is, given a collection of passwords generated by this algorithm allows an attacker to determine the internal state of System.Random and then from that they can make good guesses as to all past and future passwords that will be generated. That's bad! The whole point of a randomly-generated password is to make it hard to guess.

Use a crypto-strength PRNG instead.


Project Euler #549: Divisibility of factorials This is the problem:

  Calculate

  $$\sum_{i=2}^{10^8} s(i)$$

  where \$s(n)\$ is the smallest \$m\$ such that \$n\$ divides \$m!\$.

Quite mathematical, I've found a better way than brute force by using largest prime factor and greatest common divisor. It works fine when n = 100 but still very slow when n gets larger and far too slow to solve the problem. So of course there are better ways.

Here is the code in Python:

import math

def maxPrimeFactor(n):
    p = 2
    while (p <= n/p):
        if (n%p):
            p += 1
        else:
            n/=p
    return n

def gcd(a,b):
    c = 1
    while (b):
        c = b
        b = a % b
        a = c
    return a

def sn(n):
    solution = prod = 1
    p = maxPrimeFactor(n)
    pFac = math.factorial(p)
    if((pFac%n) == 0 and pFac>=n):
        solution = p
    else:
        rest = n / gcd(pFac, n)
        solution = p+1
        prod = p + 1
        while(prod < rest):
            solution += 1
            prod *= solution
        while (prod % rest):
            solution += 1
            prod *= solution
    return solution

sum = 0
for i in range(2,100000001):
    sum += sn(i)
print sum

Caveat: at the moment I have neither the time nor the knowledge for solving Problem Euler #549 properly - all I can offer is more effective ways of applying brute force.

The biggest obstacle to solving this problem by brute force using factorials is the sheer size of the numbers involved. Stirling's approximation says that 100000000! has more than 2 * 10^9 bits; with a good MP library like GMP such numbers might be just barely tractable but it's going to be painfully slow.

Moreover, these factorials would need to be factored, which under the circumstances would boil down to trial division by up to pi(10^8) = 5,761,455 primes - and this would give a whole new meaning to the phrase 'painfully slow'.

A much better way is to avoid factorials entirely, working (almost) exlusively in the realm of factors. The most important insight - on which all solutions presented here are based - is this:

s(p^k * m) = max(s(p^k), s(m)) if gcd(p, m) == 1

In other words (and formulated without recursion): given the factorisation of a number n, the value s(n) is the maximum s(p^k) over all distinct prime factors p.

This gives a viable recipe for computing s(n), since factorisation of small integers is trivial and the computation of s(p^k) is tractable. Here's a rendering of the latter that's not very mathematical but easy to verify and code (using C# for clarity, since I don't speak Python well enough):

// computes s(p^e) for p prime
static int s_for_prime_power (int p, int e)
{
    int k = 0;

    while (e > p)
    {
        k += p;
        e -= p + 1;

        for (int t = k; (t /= p) % p == 0; )
            --e;
    }

    return (k + Math.Max(0 , e)) * p;
}

With the help of that function the computation of s() is easily formulated:

static int s (int n)
{
    return s(factorisation(n));
}

static int s (List<int> factors, int lo = 0)
{
    int p = factors[lo], hi = lo;

    while (++hi < factors.Count && factors[hi] == p)
        ;

    int result = s_for_prime_power(p, hi - lo);

    if (hi < factors.Count)
        result = Math.Max(result, s(factors, hi));

    return result;
}

This function implements the recursion shown earlier: it determines the power of the least prime factor (by counting the number of occurrences), computes the s value for that, and then returns the maximum of that value and the s value for the rest.

I'm glossing over some unimportant things - like factorisation and so on - since Python has everything that's needed; the C# file is Euler0549_simple.linq on PasteBin. This is a script for use with the (free) LINQPad with which I do almost all of my algorithmic prototyping and Eulering/SPOJing etc. But the file is also valid .cs that can be compiled and run unchanged with Mono, for example.

This code performs suprisingly well (considering), which is nice because that makes it easier to test more advanced solutions:

# benching 'Euler0549_simple' ...

S(       10):                 39        0,0 ms
S(      100):               2012        0,0 ms
S(     1000):             136817        0,1 ms
S(    10000):           10125843        1,3 ms
S(   100000):          793183093       16,1 ms
S(  1000000):        64938007616      216,5 ms
S( 10000000):      5494373412573    3.538,4 ms
S(100000000):    #45a57e1327a02a   66.756,3 ms

In the last row some hex digits from the MD5 of the decimal result are printed, in order to avoid showing the actual result. The increase in time is higher than linear because the factorisations get longer as numbers get bigger. One major point of inefficiency here is the fact that numbers are enumerated as numbers and then factored, instead of enumerating factorisations directly.

There is a type an algorithm that effectively enumerates an initial segment of natural numbers in the form of least factor decompositions p * m where p is not greater than the least prime factor of m; see Linear time Euler's Totient Function calculation for example.

This algorithm is ideally suited for computing tables of functions where

f(p * m) = g(f(p), f(m))

which is - almost - the case here. 'Almost' because we need a decomposition of the form p^k * m with gcd(p, m) == 1; however, for a first draft this can be arranged by the simple expedient of dividing p out of m if necessary.

static int[] s;

static long E549_via_lpf_decomposition (int limit)
{
    int small_prime_limit = (int)Math.Sqrt(limit);
    var small_primes = new List<int>();
    int m = 2;

    s = new int[limit + 1];

    for (int half = limit / 2; m <= half; ++m)
    {
        if (s[m] == 0)  // prime
        {
            s[m] = m;

            if (m <= small_prime_limit)
                small_primes.Add(m);
        }

        int s_m = s[m], threshold = limit / m;

        foreach (int p in small_primes)
        {
            if (p > threshold)  // i.e. if (p * m > limit)
                break;

            if (m % p != 0)  // not a factor of m yet
            {
                // p is a new least factor -> s(p) < s(m) -> s(p * m) = s(m)
                s[p * m] = s_m;
            }
            else // p is already a (least) factor of m
            {
                int e = 2, q = m;

                while ((q /= p) % p == 0)
                    ++e;

                s[p * m] = Math.Max(s_for_prime_power(p, e), s[q]);
                break;
            }
        }
    }

    for ( ; m <= limit; ++m)
        if (s[m] == 0)
            s[m] = m;

    long sum = 0;
    for (int i = 2; i <= limit; ++i)
        sum += s[i];

    return sum;
}

This can be made more efficient in various ways but I think in this form it nicely shows the logic of the algorithm. The timings are much more linear in n, since the algorithm itself is linear. Only s_for_prime_power() and my fumbling with factoring out powers of the lpf add a tiny logarithmic influence on top:

# benching 'Euler0549_lpf_decomp' ...

S(       10):                 39        0,0 ms
S(      100):               2012        0,0 ms
S(     1000):             136817        0,0 ms
S(    10000):           10125843        0,3 ms
S(   100000):          793183093        1,9 ms
S(  1000000):        64938007616       19,5 ms
S( 10000000):      5494373412573      196,1 ms
S(100000000):    #45a57e1327a02a    1.990,3 ms

Although this is based on raw firepower instead of mathematics, it is almost decent already... Another option would be a modified Sieve of Eratosthenes (using the s[] vector like a sieve, instead of of a bit vector). Or, the devious application of advanced mathematics, but that is well beyond my capabilities ATM. ;-)


Preamble

What you're looking for is a way to obfuscate your code, not a way to encrypt it. The issue lies in the fact that the interpreter needs to have access to the unencrypted source code. This means that you have to store the key somewhere and decrypt the file before runtime, which defeats the purpose of encrypting the source code in the first place. It's almost impossible to properly protect Python code and there's lots of decompilers out there.

There's several better ways to go about doing this:

Use a restrictive (proprietary) license. Be sure to do some research on what license is best, so you know exactly what restrictions and rights people have when using your software.
If you need to interact with a (web)server, try to make as much as possible happen server-side, which, provided you secure your server, prevents people from viewing the source code.
Push frequent, backward-incompatible updates.
Think again and decide you may as well just release it under an open-source license like the MIT license or the GNU GPL.

Your code

Ram Chandra Giri covered most issues with style conventions. I'd like to point out something:

After calling open, one should call close to properly clean up. We may be tempted to do something like this:

f = open(FILENAME, MODE)
# Do stuff with `f`
f.close()

But what if an exception occurs before the close call? So, we have to wrap it in a try: | finally: statement instead:

try:
    f = open(FILENAME, MODE)
    # Do stuff with `f`
finally:
    f.close()

Python provides a cleaner way to do this, using context managers:

with EXPR as VAR:
    BLOCK

In the case of file descriptors, we can use:

with open(FILENAME, MODE) as f:
    # Do something with `f`

Specifically:

with open("save.txt", "r") as f:
    contents = f.read()
    contents = int(contents, 2)
    return contents.to_bytes(
        (contents.bit_length() + 7) // 8,
        'big'
    ).decode()

You can use sys.byteorder to find the system's native byte order. Alternatively if you want to use 'big' as byteorder, I'd make it a constant:

BYTE_ORDER = "big"

If the file is sufficiently large, the system may run out of memory trying to read it all at once. We can avoid this problem by reading 'chunks' into memory.

Here's the same code, but rewritten to implement all changes:

import sys

def write_binary_string(string, filename):
    """Convert `string` to binary and write it to `filename`.

    :param str string: The string to be obfuscated.
    :param str filename: The filename to write to.
    :raises FileNotFoundError: If `filename` is not a file.
    :return: None
    """
    with open(filename, "w") as f:
        binary_representation = bin(int.from_bytes(
            string.encode("utf-8"),
            sys.byteorder
            )
        )
        f.write(binary_representation)

def read_binary_string(filename):
    """Open `filename` and return the deobfuscated contents.

    :param str filename: The file to read from.
    :raises FileNotFoundError: If `filename` is not a file.
    :return: None
    """
    CHUNK_SIZE = 65536
    binary_representation = []
    with open(filename, "r") as f:
        while True:
            chunk = f.read()
            if not chunk:
                break
            binary_representation.append(chunk)
    binary_representation = "".join(binary_representation)
    return int(binary_representation, 2).to_bytes(
        (binary_representation.bit_length()+7) // 8,
        sys.byteorder
    ).decode("utf-8")


Finding if value exists in any column recursively Our company uses an old version of JAXB so it does not allow generics. Other than that, I am using recursive calls because Rows can have subrows and I want to find out if any of the rows for the given column id i has any values.

I am interested to know if I got the recursion right.

private static boolean anyCellHasValue(CommonRowType row, int i) {

    CustomCellType cell = (CustomCellType)row.getCustomRow().getCell().get(i);

    if(!CELL_EMPTY.equals(cell.getType())) {
        return true ;
    }

    if (row.getChildren() != null && row.getChildren().getRowData() != null &&
        !row.getChildren().getRowData().isEmpty()) {
        for (int k = 0; k < row.getChildren().getRowData().size(); k++) {
            if(anyCellHasValue((CommonRowType) row.getChildren().getRowData().get(k), i)) {
                return true;
            }
        }
    }

    return false;
}

This site is more about the readability and structure of code rather than actual correctness. I will comment on that and maybe a more readable program will help you find any potential errors?

I would recommend that you:

Extract complex if statements to their own methods describing the test
Use the new style java iteration instead of the old for loop
Reduce the block nesting level by returning early when you know you have a negative match
Use good naming for all variables. In this case the variable i desperately needs a better name!

This should produce (sans renaming of i) code that look something like this: (not compiled or tested in any way :))

private static boolean anyCellHasValue(CommonRowType row, int i) {
    if (isNonEmptyCellType(row, i)) {
        return true;
    }

    if (!hasChildren(row)) {
        return false;
    }

    for (CommonRowType childRow : row.getChildren().getRowData()) {
        if (anyCellHasValue(childRow, i)) {
            return true;
        }
    }

    return false;
}

private static boolean isNonEmptyCellType(CommonRowType row, int i) {
    CustomCellType cell = (CustomCellType)row.getCustomRow().getCell().get(i);
    return !CELL_EMPTY.equals(cell.getType()));
}

private static boolean hasChildren(CommonRowType row) {
    return row.getChildren() != null
            && row.getChildren().getRowData() != null
            && !row.getChildren().getRowData().isEmpty();
}


Search father (x) of the number D(x) and measure time and memory consumed We define function D(x) as following:

D(x) = x + sum of digits of x
+ sum of prime factors of x   then call x the father of D(x)

Write a program that gets input t at the first line and then gets an input in the next t lines. If that input had father, print YES otherwise NO

For example 12 is the father of 20
20 = 12 + (1 + 2) + (2 + 3)

preferably write a separate function for each of these tasks:

Getting sum of the digits of a number
Getting prime factors of a number
Calculating D(x)

Notice that if you do lots of operations, you may get time limit error.

Time limit: 0.5 seconds
Memory limit: 128 MB

Input:
You get an input number t at the first line and then in the next t lines, you get number n for which you should solve the problem

Output:
Print the answer to each input in t lines.

Example:
Sample input:

  2
  4
  20

Sample output:

  NO
  YES

I've written the code with python:

# function that returns the unique prime factors of number n as a list
def prime_factors(n):
    i = 2
    factors = []
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
            factors.append(i)
    if n > 1:
        factors.append(n)
    factors = list(set(factors))
    return factors

# function that returns the sum of digits of number n
def sum_digits(n):
    r = 0
    while n:
        r, n = r + n % 10, n // 10
    return r

# function to calculate the offspring of number X {D(X)}
def Offspring(X):
    DX = X + sum(prime_factors(X)) + sum_digits(X)
    return DX

ChildFather = {i: Offspring(i) for i in range(4, 1001)}
ChildFatherValues = list(set(list(ChildFather.values())))
ChildFather.clear()
Fathers = [i for i in ChildFatherValues if i <= 1000]
ChildFatherValues.clear()
t = eval(input())
for i in range(0, t):
    n = eval(input())
    if n in Fathers:
        print('YES')
    else:
        print('NO')

I guess this part of code

ChildFather = {i: Offspring(i) for i in range(4, 1001)}
ChildFatherValues = list(set(list(ChildFather.values())))
ChildFather.clear()
Fathers = [i for i in ChildFatherValues if i <= 1000]
ChildFatherValues.clear()

is the bottle-neck for time limit. since I don't know how to find x by having D(x), I've solved the problem this way:

ChildFather = {i: Offspring(i) for i in range(4, 1001)}

for numbers 4<= n<= 1000, I've created a dictionary {n:D(n)}

ChildFatherValues = list(set(list(ChildFather.values())))
ChildFather.clear()

created a list of unique values of the dictionary and deallocated the memory used for the dictionary

Fathers = [i for i in ChildFatherValues if i <= 1000]
ChildFatherValues.clear()

create a list of values smaller than 1000 and deallocated memory used for the original list

t = eval(input())
for i in range(0, t):
    n = eval(input())
    if n in Fathers:
        print('YES')
    else:
        print('NO')

If a given number exists n in the final provided list, I understand that n can be written as D(m)=m+sum of digits of m + sum of prime factors of m so n has the father m and I'll print Yes otherwise NO
But seems that the program is not efficient.

How can I measure the time consumed by this python program at run-time?
How can I measure the memory consumed by this python program at run-time?
(I'm new to python and am coding with sublime text 3 in Linux Ubuntu)
Is there any more efficient way of writing the code?

PEP-8
Try to stick to PEP-8. So snake_case for variable and method names and a lot of other guidelines. Check any other Code Review Python post for tips from people who can explain this better than me.
Memory
Since you have 128MB of memory available, and a list of 1000 integers (l = list(range(1000)); sys.getsizeof(l) + sum(map(sys.getsizeof, l))) takes only 37kb on my system, I would not worry about clearing intermediate results.
Pre-calculate the primes to 1000
If the input number never goes beyond 1000, pre-calculating all the primes will be the fastest and most efficient. Here is method rwh_primes from this SO post adapted for Python 3:
def primes(n):
    # https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
    """ Returns  a list of primes < n """
    sieve = [True] * n
    for i in range(3, int(n ** 0.5) + 1, 2):
        if sieve[i]:
            sieve[i * i :: 2 * i] = [False] * ((n - i * i - 1) // (2 * i) + 1)
    return [2] + [i for i in range(3, n, 2) if sieve[i]]

This takes about 50µs on my PC.
prime_factors
You do some of unnecessary calls to set and list. I would implement this as a generator, and store it further upstream as a set:
def prime_factors(n):
    for factor in PRIMES:
        if factor > n**.5:
            yield n
            return
        while not (n % factor): # n is divisible by factor
            yield factor
            n //= factor
            if n == 1:
                return

sum_digits
This one looks okay. You could use divmod, but that is a matter of taste.
offspring
No need for the intermediate DX:
def offspring(x):
    return x + sum(set(prime_factors(x))) + sum_digits(x)

Main guard
Keep the main logic behind a if __name__ == '__main__': guard.
eval
Instead of using eval, since you know it will be int, better use int(). eval can be dangerous, since it can execute arbitrary code. If you need to interpret a python literal, use ast.literal_eval.
Then you do something very inefficient by creating a dict, then take only the values, apply list, set and list again. Easiest would be to just use a set-comprehension:
all_offspring = {offspring(i) for i in range(1, 1001)}

This will include some numbers over 1000, but this extra memory should be negligible.
Test
You can spoof input on your system by something like
test_case = '''2
4
20'''
input = iter(test_case.split('\n')).__next__

main
if __name__ == '__main__':
    PRIMES = primes(1000)
    all_offspring = {offspring(i) for i in range(1, 1001)}
    t = int(input())
    for i in range(t):
        n = int(input())
        if n in all_offspring:
            print('YES')
        else:
            print('NO')

Timing
To time it you can use timeit module. There are enough posts on SO about this, and for memory usage.


Dividing valuable items so that two persons get the most similar value possible You have n items, each one of those has a certain value, represented here as an integer.
  How do you give to two persons the most similar value?

No comment from me here as my code already contains much documentation.

from itertools import combinations, chain
import doctest

def all_subsets(lst):
    """
    Returns all the possibilities of taking n elements of the
    lst, where n goes from 0 to len(lst) - 1

    >>> list(all_subsets([1,2,3]))
    [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3)]
    """
    return chain.from_iterable(combinations(lst, i) for i in range(len(lst)))

def partitions(items):
    """
    All the possible ways to divide the items in two.

    >>> list(partitions([1,2,3]))
    [((1,), (2, 3)), ((2,), (1, 3)), ((3,), (1, 2)), ((1, 2), (3,)), ((1, 3), (2,)), ((2, 3), (1,))]
    """
    return ((a,b)
             for a in all_subsets(items)
               for b in all_subsets(items)
                 if set(a).union(set(b)) == set(items) and\
                    not set(a).intersection(set(b)))

def evenly_divide(items):
    """
    You have n items, each one of those has a certain value,
    represented here as an integer.

    How do you give to two persons the most similar value?

    This problem is NP-complete.
    This function finds the optimal solution by bruteforce.

    >>> evenly_divide( [1,2,3] )
    ((3,), (1, 2))
    >>> evenly_divide( [9, 12, 14, 17, 23, 32, 34, 40, 42, 49] )
    ((9, 12, 32, 34, 49), (14, 17, 23, 40, 42))
    """
    def difference(parts):
        first_part, second_part = parts
        return abs(sum(first_part) - sum(second_part))

    return min(partitions(items), key=difference)

def fevenly_divide(items):
    """
    You have n items, each one of those has a certain value,
    represented here as an integer.

    How do you give to two persons the most similar value?

    This problem is NP-complete.

    This function finds an approximate solution by sorting the items, and
    then giving the next item to the most poor guy.

    >>> fevenly_divide( [1,2,3] )
    ([2, 1], [3])
    >>> fevenly_divide( [9, 12, 14, 17, 23, 32, 34, 40, 42, 49] )
    ([42, 40, 32, 14, 9], [49, 34, 23, 17, 12])
    """
    first_guy = []
    second_guy = []
    for item in reversed(sorted(items)):
        if sum(first_guy) < sum(second_guy):
            first_guy.append(item)
        else:
            second_guy.append(item)
    return first_guy, second_guy

if __name__ == "__main__":
    doctest.testmod()

partitions

This is inefficient since
once you have one person's items you know what the other person's items are - just take the complement.

Also - does this condition really work if two items have the same value?

   if set(a).union(set(b)) == set(items) and\
        not set(a).intersection(set(b)))

For instance, what if the values of the items are [3,3,3,3]?

This suggests that you should partition the item ids - not the item values.

Here is an example of what I'm getting at:

def evenly_divide(vals):
  ids = range(len(vals))
  total = sum(vals)
  half = total / 2

  bestSum = 0
  bestIds = []
  for a in all_subsets(ids):
    s = sum( vals[i] for i in a )
    if 2*s <= total and s > bestSum:
        bestSum = s
        bestIds = a
        if 2*s == total: break -- no need to continue
  return (bestSum, bestIds) # returns items for one person

This is still very inefficient, but it's more direct and concise.


Construct intervals from a sequence of numbers and vice versa What is a Pythonic way to construct intervals from a sequence of integer numbers? E.g. sequence [1, 2, 3, 6, 7, 9] could be converted to ['1-3', '6-7', '9']. I have implemented it like this:

def sequence_to_intervals(seq):
    intervals = []
    interval_start = None
    interval_end = None
    for i in sorted(seq):
        if interval_start is None:
            interval_start = i
            interval_end = i
        elif interval_end + 1 >= i:
            interval_end = i
        else:
            if interval_start == interval_end:
                intervals.append(str(interval_start))
            else:
                intervals.append(f'{interval_start}-{interval_end}')
            interval_start = i
            interval_end = i
    else:
        if interval_start == interval_end:
            intervals.append(str(interval_start))
        else:
            intervals.append(f'{interval_start}-{interval_end}')
    return intervals

Simple test:

seq = [1, 2, 3, 6, 7, 9]
sequence_to_intervals(seq)
['1-3', '6-7', '9']

Converting intervals back to sequence:

def intervals_to_sequence(intervals):
    seq = []
    for interval in intervals:
        if '-' in interval:
            start, stop = interval.split('-')
            seq += list(range(int(start), int(stop) + 1))
        else:
            seq += [int(interval)]
    return seq

Simple test:

intervals = ['1-3', '6-7', '9']
intervals_to_sequence(intervals)
[1, 2, 3, 6, 7, 9]

For the first part of making sequence to intervals, you could do this instead (prob. more Pythonic?)  (This can be converted to a function easier - leave for the exercise)
>>> # if x-1 not in seq:  x becomes start point
>>> # if y+1 not in seq:  y becomes end point
>>> starts = [x for x in seq if x-1 not in seq]
>>> ends =  [y for y in seq if y+1 not in seq]
>>> ends
[3, 7, 9]
>>> intervals = [str(a)+'-'+str(b) for a, b in zip(starts, ends)]
>>> intervals
['1-3', '6-7', '9-9']
>>>

[Note - last interval could be 'fixed' too  - if we see start_point == end_point. Leave as an exercise.]
Then for the second part, it would be quite similar:
>>> seq = []
>>> for inter in intervals:
    s, e = inter.split('-')
    seq += list(range(int(s), int(e)+1))
>>> seq
[1, 2, 3, 6, 7, 9]