Python Friendly Form The 'friendly form' of a number is written as a sum of reciprocals of distinct positive integers. eg. $$\frac{4}{5} = \frac{1}{2} + \frac{1}{4} +\frac{1}{20}$$

I have written a python program that calculates the friendly form of an inputted fraction.

import math
from fractions import Fraction

def decompose(x):
    if x.numerator == 1:
        return [x]

    # Finds the largest fraction m = 1/p which is less than or equal to x
    m = Fraction(1, math.ceil(float(1 / x)))
    x = x - m

    #Recursively returns a chain of fractions
    return decompose(x) + [m]

def main():
    inp = input("Enter positive fraction in form \"a/b\": ")

    try:
        x = Fraction(inp)
    except ValueError:
        print("Invalid input.")
        return

    if float(x) == 0:
        print("Enter non-zero value.")
        return

    if float(x) < 0:
        print("Converting to positive value.")
        x = -x

    if float(x) >= 1:
        print("Enter valid fraction")
        return

    answer = decompose(x)
    for a in answer:
        print(a)

if __name__ == "__main__":
    main()

Overall, the code is very good, but a few tiny improvements can be made:

In the decompose function x = x - m can be replaced with x -= m
Instead of return decompose(x) + [m] and such, use yield
Instead of for a in answer ..., use print(*answer, sep='\n')
In the decompose function, math.ceil(float(1 / x)) can be changed to math.ceil(1 / x). Python 3.x automatically interprets / as a float operator
As only math.ceil is used, you could just do from math import ceil

Here's the final code:

from math import ceil
from fractions import Fraction

def decompose(x):
    if x.numerator == 1:
        yield x
        return

    m = Fraction(1, ceil(1 / x))
    x -= m

    yield m
    yield from decompose(x)

def main():
    inp = input("Enter positive fraction in form 'a/b': ")

    try:
        x = Fraction(inp)

    except ValueError:
        print("Invalid input.")
        return

    if float(x) == 0:
        print("Enter non-zero value.")
        return

    if float(x) < 0:
        print("Converting to positive value.")
        x = -x

    if float(x) >= 1:
        print("Enter valid fraction")
        return

    print(*decompose(x), sep='\n')

if __name__ == "__main__":
    main()

Hope this helps!


Method for populating ListViewSubItems This is my current method for populating the sub-items of ListView controls. I like this method for two reasons...

1) I don't have to keep up with the display order of the columns.

2) If I enable column re-ordering, I don't have to change anything with the code.

So, the question is... Is this a good approach? Can it be improved?

Note: I'm not too happy about declaring Result As Object. It seems like there should be a better way to handle that, but it's the only way I could get it to working.

Private Function RetrieveItem(Of T)(ByVal displayIndex As Integer) As T
    Dim Result As Object = If(GetType(T) Is GetType(ListViewItem), New ListViewItem, New ListViewItem.ListViewSubItem)
    Select Case displayIndex
        Case ColumnHeader1.DisplayIndex
            Result.Text = "First Item"
            Result.Tag = "First"
        Case (ColumnHeader2.DisplayIndex)
            Result.Text = "Second Column"
            Result.Tag = "Second"
        Case ColumnHeader3.DisplayIndex
            Result.Text = "Third Column"
            Result.Tag = "Third"
        Case ColumnHeader4.DisplayIndex
            Result.Text = "Fourth Column"
            Result.Tag = "Fourth"
    End Select
    Return Result
End Function

Example Usage...

Dim item As ListViewItem = RetrieveItem(Of ListViewItem)(0)
For i As Integer = 1 To ListView1.Columns.Count - 1
    item.SubItems.Add(RetrieveItem(Of ListViewItem.ListViewSubItem)(i))
Next
ListView1.Items.Add(item)

Here is the example I came up with using @MarkHurd's suggestion of using a Widening CType Operator...

Private Class LVI
    Public Name As String
    Public Text As String
    Public Tag As Object
    Public Sub New(ByVal name As String, ByVal text As String, ByVal tag As Object)
        Me.Name = name
        Me.Text = text
        Me.Tag = tag
    End Sub
    Public Shared Widening Operator CType(ByVal item As LVI) As ListViewItem
        Dim Result As New ListViewItem(item.Text)
        Result.Name = item.Name
        Result.Tag = item.Tag
        Return Result
    End Operator
    Public Shared Widening Operator CType(ByVal item As LVI) As ListViewItem.ListViewSubItem
        Dim Result As New ListViewItem.ListViewSubItem
        Result.Text = item.Text
        Result.Name = item.Name
        Result.Tag = item.Tag
        Return Result
    End Operator
End Class

Private Function RetrieveItem(ByVal index As Integer) As LVI
    Select Case index
        Case ColumnHeader1.DisplayIndex : Return New LVI("1", "First Column", "one")
        Case ColumnHeader2.DisplayIndex : Return New LVI("2", "Second Column", "two")
        Case ColumnHeader3.DisplayIndex : Return New LVI("3", "Third Column", "three")
        Case ColumnHeader4.DisplayIndex : Return New LVI("4", "Fourth Column", "four")
        Case Else : Return Nothing
    End Select
End Function

Example usage...

Dim item As ListViewItem = RetrieveItem(0)
For i As Integer = 1 To ListView1.Columns.Count - 1
    item.SubItems.Add(RetrieveItem(i))
Next
ListView1.Items.Add(item)

I like both of these approaches, but I feel like the first is shorter and easier to implement, so I lean towards the first option.

If you want to avoid the late bound .Text and .Tag you could just create your own private type, say LVI, containing these two properties and implicit Widening CType operators for ListViewItem and ListViewItem.ListViewSubItem. Then the Result As New LVI can be converted on return using Return CType(CTypeDynamic(Result, GetType(T)), T) in the latest VB.NET.

Without CTypeDynamic I don't have a working solution yet.


Python code that compares two files byte by byte I wrote a Python (2.7) script that compares a file byte by byte. filecmp was not suitable for the application because it compares metadata as well. How can I improve this code?

def byte_comp(fname, fname2):
    """
        Compares two files byte by byte
        Returns True if the files match, false otherwise
    """
    read_size = 1048576 # Determined experimentally
    if os.path.getsize(fname) != os.path.getsize(fname2): # If two files do not have the same size, they cannot be same
        return False
    with open(fname, "rb") as f:
        with open(fname2, "rb") as f2:
            count = 0 # Counts how many bytes have been read
            while count <= os.path.getsize(fname): # Loops until the whole file has been read
                if(f.read(read_size) != f2.read(read_size)): # If the chunk of the file is not the same, the function returns false
                    return False
                count += read_size
    return True # If the files are the same, it returns True

I would also appreciate help on how to make the function faster and less CPU intensive.

The code in the post calls os.path.getsize for each block read from the two files. This could be avoided by remembering the value in a local variable.
The code accumulates count in order to detect the end of the files being compared. But the read method will return an empty bytes object when the end of file is reached, so there is no need to maintain a count.

If you look at the implementation of the filecmp module, you'll see that file comparison is implemented like this:

def _do_cmp(f1, f2):
    bufsize = BUFSIZE
    with open(f1, 'rb') as fp1, open(f2, 'rb') as fp2:
        while True:
            b1 = fp1.read(bufsize)
            b2 = fp2.read(bufsize)
            if b1 != b2:
                return False
            if not b1:
                return True


Efficient way to copy unordered String into ordered String I'm doing this in Hadoop Java where I'm reading a String. The string is huge that has been tokenized and put in an array. It has key-value pairs but they are not in any order. I want this order to be rigid so I can load that as a table. So in SQL, if I select a column (after loading this in a table), all the keys of one type should be in colA.

I'm checking each word of the String array and copying them in a new string in a fixed position. The way I thought of doing this is using if else ladder like this:

//row is the tokenized unordered String

String[] newRow = new String[150];

for (int i = 0; i < row.length; ++i) {

    if(row[i].equals("token1")){
        newRow[0] = row[i]; //key
        newRow[1] = row[i+1];//value
    }

    else if(row[i].equals("token2")){
        newRow[2] = row[i];
        newRow[3] = row[i+1];
    }//...and so on. Elseif ladder at least is at least 100 long.

I wanted to know if there is a more efficient way to do this?

PS: I'm not sorting the string. Example: row1 String is {apple,good,banana,bad}, row2 String is {banana,good,apple,bad} where apple and banana are keys. Now in my output I will have two records with say apple as the first key and then banana. So output will be : newRow1: {apple,good,banana,bad}, newRow2: {apple,bad,banana,good}. Essentially I'm rearranging all input to a fixed output.

I'd put token names and positions in a Map like this:

Map<String, Integer> tokenIndexes = new HashMap<String, Integer>();
tokenIndexes.put("token1", 0);
tokenIndexes.put("token2", 2);
tokenIndexes.put("token3", 4);
// ...

and then in the "sorting" part:

String[] newRow = new String[150];

for (int i = 0; i < row.length; i+=2) { // go two by two as you have keys in even indexes
    if(tokenIndexes.contains(row[i])) {
        int index = tokenIndexes.get(row[i]);
        newRow[index] = row[i];
        newRow[index + 1] = row[i + 1];
    } else {
        // handle missing token
    }
}

This way I would get rid of all "if-else" statements, although now I have to maintain a Map (which I think is easier than maintaining a list of "if-else").

UPDATE

I'm supposing you just receive that String array and you're unable to change the way the information is retrieved. If you can change the initial array with a Map that would simplify your code even further.

If that's the case then try this to capture your tokens instead of putting everything in an array (I'm supposing a key is the first token to appear):

Map<String, String> info = new HashTable<String, String>();
boolean isKey = true;
String lastKey = null;
String token;
while(tokensAvailable()  /* or (token = readToken()) != null */) {
    token = readToken();
    if(isKey) {
        lastKey = token;
    } else {
        info.put(lastKey, token);
    }
    isKey = !isKey;
}

And then when you have to print your table, you can do something like this:

printOut("VAL_1    --   VAL_2   --   VAL_3");
printOut(String.format("%08d  --  %10.2  -- %s", info.get("numericVal1"), info.get("monetaryVal2"), info.get("val3")));

String.format() is useful in these cases, you can control the format (like the width) of how every field is printed.


Minimise function with single minimum and no maximums I'm learning F#. I wrote a function to minimise a function with a single minimum and no maximums. At the bottom I test it on Math.Cos.

What do you think? I've wrote it pretty much as I would in an imperative language. Could it be done more functionally?

/// <summary>Assuming f is a continuous function with a single minimum and
/// no maximums in (lower,upper), find the minimum point.</summary>
let rec minimise f (lower:float) (upper:float) =
    let lmid = (2.0*lower+upper)/3.0
    let umid = (lower+2.0*upper)/3.0
    if lmid = lower && umid = upper then
        Seq.minBy f [lower; upper]
    else if f lmid < f umid then
        minimise f lower umid
    else
        minimise f lmid upper

let solution = minimise Math.Cos 0.0 6.0
printf "solution: %g" solution
printf "absolute error: %g" (solution - Math.PI)

This is actually pretty functional.

The only thing I'd recommend is to avoid comparing floating-point numbers for exact match. Because arithmetic happens in binary, not in decimal, multiplying and dividing by nice-looking decimal numbers will produce ugly-looking binary ones, and more importantly, lose precision. As a result, depending on the input, your terminating condition may literally never become true - e.g. lmid may come out just a bit higher than lower at every step, and your function will recurse indefinitely.

The bottom line is, you can't trust direct comparison of floating-point numbers. Instead, compare their difference with a very small number (aka "margin of error"). But even then, you can't just use a constant for this, because you never know if it will be "small enough" for the inputs. The accepted way of doing this is to use a fraction of the inputs - aka "relative margin of error" (as opposed to "absolute").

 if x = y ...  // bad
 if abs (x-y) <= 0.00001 ... // better
 if abs (x-y) <= (abs x * 0.00001) ... // even better


Replacing all occurrences in a String I have a string like this :

val content = "some_text{macro1}another_text{macro2}text"

I want to replace the {macro1} and {macro2} with macro1 and macro2, i.e. just to remove the { and }.

I wrote some piece of code which works fine, but for me it seems very hard to read:

val Pattern = """\{(.*)\}""".r

Pattern.findAllIn(content).matchData.foldLeft(content) ( (newContent: String, current: Regex.Match) => {
     newContent.replace(current.group(0), current.group(1))
   }
)

How I can improve this code? Please note: since it's in Scala, I prefer it in the functional way.

Your desire to use the "functional way" is not well-motivated. Why do it "the functional way" when the "other way" is not only easier to read, but also common practice, and well-understood?

val stripCurly = "[{}]".r

val replaced = stripCurly.replaceAllIn(a, "")

If you want to have forced-matching of the braces consider:

val pure = """\{([^}]*)\}""".r
val pured = pure.replaceAllIn(content, "$1")

Note the use of the "not a } inside the {}" logic in the regex.

The examples above are running here in ideone


Is there a better way to update fields in an web app? This is the stripped down version of my update action for a Posts (blog post) controller:

Posts.update = function(req, res){
    _.extend(req.post, {
        title: req.body.title
    ,   author: req.body.author
    ,   body: req.body.body
    });
    post.save();
};

This way feels a bit clumsy and repetitive, because I have similar code in another method, but I don't want to just straight up _.extend(req.post, req.body) because it may allow someone to change fields that shouldn't be changed  in my models.

Is there a better middle ground?

How about _.pick()?

Posts.update = function(req, res){
    _.extend(req.post, _.pick(req.body, 'title', 'author', 'body'));
    post.save();
};


Very simple stack in C I'm starting to learn C and thought it would be a good idea to try and implement some data structures. I started with a very simple stack and would like to hear some opinions.

Stack.c

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

struct Node {
    int element;
    struct Node* next;
};

struct Node* head;
int size;

int stack_init() {
    struct Node* dummy = malloc(sizeof(struct Node));
    if(dummy == NULL) {
        return -1;
    }
    head = dummy;
    return 0;
}

int push(int value) {
    struct Node* tmp = malloc(sizeof(struct Node));
    if (tmp == NULL) {
        return -1;
    }
    tmp->element = value;
    tmp->next = head;
    head = tmp;
    size++;
    return 0;
}

int pop() {
   if(size == 0) {
        printf("Stack is empty\n");
    }else {
        printf("Element #%d ->value: %d  has been removed\n", size, head->element);
        free(head);
        head = head->next;
        size--;
    }
    return 0;
}

void print_stack() {
    struct Node* tmp = head;
    printf("Stacksize: %d\n", size);
    for(int i = 0;i < size;i++) {
        printf("Element %d -> %d\n",i,tmp->element);
        tmp = tmp->next;
    }
    printf("#####################\n");
}

int get_size() {
    return size;
}

Stack.h

#ifndef STACK_H
#define STACK_H

int stack_init();

int push(int value);

int pop();

void print_stack();

#endif

I see a number of things that may help you improve your code.

Use a stack pointer as a parameter

Right now, one can only have one stack at a time.  Worse, if one calls stack_init after some items have already been pushed onto the stack, there will be a memory leak.  An alternative scheme would be to have stack_init() return a pointer to a Stack and then use that as a parameter for all other calls.  That way, one could have multiple stacks simultaneously, making it that much more useful.

Initialize all values before use

In the stack_init routine, the head variable is initialized, but neither head->element nor head->next are initialized.  It's also probably a good idea to explicitly zero the size.  Although it's already zeroed at the moment because it's a file scope variable, if you follow the other advice on this list, you'll have to initialize it yourself.

Provide a way to free memory

Right now, the only way to free memory is to repeatedly call pop().  Unfortunately, the calling program has no way to know how many items are on the stack or to know when the stack is empty, so it's not going to be able to know how many times to do so.  I'd suggest providing at least an explicit isEmpty() call.

Provide a complete interface

At the moment, there isn't any way to actually use the stack except to call print_stack() which limits its usefulness in the extreme.  I'd suggest that adding a means of examining the top of the stack, as with a call to top() that returns the value for that item might be a good idea.

Don't access freed memory

These lines have a problem:

free(head);
head = head->next;

The problem is that after you've freed head, you dereference it to get the next pointer.  This is undefined behavior -- anything could happen and it probably won't be good!  Better would be to save a copy of the pointer, do your housekeeping and then free the copy like this:

struct Node* temp = head;
head = head->next;
free(temp);

Separate printing from data manipulation

There is no way at the moment to use pop without it printing something.  In a real program that use such a stack, that's unlikely to be the desired effect.  Better would be to have pop() just do what it needs to do and leave printing to the calling program.

Return something useful from functions

Most of your non-void functions return something useful, but pop always returns 0 which isn't very useful.

Encapsulate related data in a structure

The size and head elements are closely related items.  For that reason (and to accomodate suggestion #1 on this list), I'd recommend combining them into a struct instead like this:

struct Stack {
    struct Node* head;
    int size;
};

Use a typedef to simplify your code

If you use a typedef like this:

typedef struct {
    struct Node* head;
    int size;
} Stack;

the code can refer to simply Stack instead of struct Stack.  It's not necessary, but it does tend to make things a little easier to write and to read.


Python pattern searching using re standard lib, str.find() I'm trying to improve some code in order to get a better perfomance, I have to do a lot of pattern matching for little tags on medium large strings, for example:

import re
STR = "0001x10x11716506872xdc23654&xd01371600031832xx10xID=000110011001010\n"

def getID(string):
    result = re.search('.*ID=(\d+)', string)
    if result:
        print result.group(1)
    else:
        print "No Results"

Taking in mind the perfomance I rewrite it:

def getID2(string):
    result = string.find('ID=')
    if result:
        result += 3
        print string[result:result+15]
    else:
        print 'No Results'

Are there a better way to improve these approaches?
Any comments are welcome...

If you name your function getSomething(), I expect it to return a value with no side effects.  I do not expect it to print anything.  Therefore, your function should either return the found string, or None if it is not not found.

Your original and revised code look for different things: the former wants as many digits as possible, and the latter wants 15 characters.  Combining the two requirements, I take it that you want 15 digits.

re.search() lets the regular expression match any part of the string, rather than the entire string.  Therefore, you can omit .* from the beginning of your regular expression.

Here's how I would write it:

import re
STR = "0001x10x11716506872xdc23654&xd01371600031832xx10xID=000110011001010\n"

def getID(string):
    result = re.search('ID=(\d{15})', string)
    return result and result.group(1)

print getID(STR) or "No Results"


If statement, is the shortened version readable enough? I have to perform an IF statement in my Javascript code. I utilised the first method shown below:

(someVar1 !== "someString") && (someVar2[i].disabled = (someVar3.find("." + someVar4).length == 0));

Is the shortening of an if like this ok to do if my code is to be viewed by other members of my team? I have been told that it is a bit unclear and should instead use something like the following instead:

if (someVar1 !== "someString") {
  var bool = someVar3.find("." + someVar4).length == 0;
  someVar2[i].disabled = bool;
}

What are people's thoughts on this? Was it reasonable for me to implement the first method? Was it fair for me to be told I should change it and not use the (someVar) && doThis version of an if?

The second part of the condition in the first method (someVar2[i].disabled = (someVar3.find("." + someVar4).length == 0)) is only an assignment and is always evaluated to true.

It is clearer to use only the first part of the condition as a condition in if (someVar1 !== "someString") and move assignment inside the if statement, similarly as you did in the second method.

Regarding the second method, I would avoid using names such as bool as they are keywords. Use another name instead.

Also, in this particular case you are assigning value to variable 'bool' and then use it only once. You could assign the value directly to someVar2[i].disabled.

if (someVar1 !== "someString") {
  someVar2[i].disabled = someVar3.find("." + someVar4).length == 0;
}

You could also use inline if:

someVar2[i].disabled = (someVar1 !== "someString") ? (someVar3.find("." + someVar4).length == 0) : <defaultValue>;


Finding the balancing point of a subsequence This is a little tricky to explain, so bear with me.
Suppose you have an integer X and a list of integers A.  Let A` be a copy of A where all values A[i] != X are replaced by -X.  For example,
X = 5
A = [1, 3, 5, 5, 1, 5, 4, 1, 8]

would result in
A` = [-5, -5, 5, 5, -5, 5, -5, -5, -5]

The task is to find a subsequence B of A` that sums to 0 when the middle
item of B is removed from the summation.  With the previous example we would have
B = [-5, 5, 5, -5, 5, -5, -5]

where the middle item is -5 at index 4 (of A`).  Splitting that into two lists generates
[-5, 5, 5] | [5, -5, -5]

which clearly sum to 0.  If such a subsequence B exists then the program should return the index of that middle value, plus 1.  In this case the return value would be 5.
I have a working solution, however it has pretty bad time complexity:

4.64179955720276e-05 for 15 elements
0.003033149677870525 for 115 elements
0.15060318663344355  for 1015 elements
13.662074328908023   for 10015 elements

It is supposed to scale up to 100,000 elements, and I think that would take about 19 minutes in the current state.  I'd greatly appreciate any suggestions on how I could simplify, improve, and speed up my algorithm.
from collections import deque

def equi ( trim_list ):
    popped_total = sum(trim_list)
    j = popped_total
    k = 0
    center = 0
    for elem in trim_list:
        j = j - elem
        if j+k == 0:
            return center + 1  # list index of sequence middle index
        k = k + elem
        center += 1
    return -1  # no match found

def solution(X, A):
    # Break from function because list too small
    if not len(A) > 5:
        return -1

    # zero out non X values into reciprocal for equality approach
    # use deque for efficient 0 index removal Lifo queue also works
    equi_deque = deque(X if elem is X else 0 for elem in A)

    # iterate through deque and pop values if they fail an equality check
    while len(equi_deque) > 4:
        # is_sequence = equality_point(X, equi_deque)
        is_sequence = equi(list(equi_deque))
        # if value did not fail return index
        if is_sequence != -1:
            # use offset to account for prior elements popped
            return len(A) - len(equi_deque) + 1
        equi_deque.popleft()
    return -1

Without messing with your actual algorithm, right now it's effectively \$O(n^2)\$.

Creating the initial deque is \$O(n)\$
The while loop is essentially \$O(n)\$ (worst case)
Within the while loop you call equi with successively smaller lists \$k=(n, n-1, n-2, \dots, n-5)\$ and equi is \$O(k)\$ (worst case).

So the loop is \$O(n^2)\$ and dominates.

You can get some improvement in running time vs complexity though (maybe 20%) by fixing this line:

is_sequence = equi(list(equi_deque))

to be

is_sequence = equi(equi_deque)

The conversion to a list is unnecessary, and is an \$O(k)\$ operation.


Determine indentation of a line of code The following function determines the amount of indentation of a string. It returns two values. The first is an effective indentation where tabs are expanded such that their end aligns with 4 spaces steps. The second is just the amount of spaces and tabs before the first non-tab/space character.

roundup is a method that rounds the first argument to next higher multiple of the second argument. The rest is standard CL.

(defun indentation (line)
  (let ((spaces 0))
    (dotimes (index (length line) (values spaces index))
      (case (aref line index)
        (#\Space (incf spaces))
        (#\Tab (setf spaces (roundup (1+ spaces) 4)))
        (otherwise (return (values spaces index)))))))

I don't like having to state the return value twice.

I guess roundup is something like
(defun roundup (x y) (* (ceiling x y) y))?

For the reason you stated I'd probably go with loop (or alternatives,
iterate comes to mind) instead of the do... family of macros, e.g.:

(defun indentation (line)
  (loop
    with spaces = 0
    for index below (length line)
    do (case (char line index)
         (#\Space (incf spaces))
         (#\Tab (setf spaces (roundup (1+ spaces) 4)))
         (T (loop-finish)))
    finally (return (values spaces index))))

Depending on the choice of input you might want to use char for
strings instead of aref.
otherwise is pretty long, but of course it's somewhat of a personal
choice - t is a bit shorter.


Shifting event times to and from time zones I have getOffseSeconds method:

private int getOffsetSeconds(LocalDateTime localDateTime, ZoneId zoneId) {
    return ZonedDateTime.of(localDateTime, zoneId).getOffset().getTotalSeconds();
}

This method is used in shifted LocalDateTime calculation

private void shiftEventDateTimeToOriginalZone(EventDto event) {
    event.setStartDateTime(event.getStartDateTime().plusSeconds(
            getOffsetSeconds(event.getStartDateTime(), event.getStartDateTimeZone())));
    event.setEndDateTime(event.getEndDateTime().plusSeconds(
            getOffsetSeconds(event.getEndDateTime(), event.getEndDateTimeZone())));
}

Now I need similar method to last one but with small change:

private void shiftEventDateTimeToDefaultZone(EventDto event) {
    event.setStartDateTime(event.getStartDateTime().minusSeconds(
            getOffsetSeconds(event.getStartDateTime(), event.getStartDateTimeZone())));
    event.setEndDateTime(event.getEndDateTime().minusSeconds(
            getOffsetSeconds(event.getEndDateTime(), event.getEndDateTimeZone())));
}

As you can see, the difference is in using methods: plusSeconds and minusSeconds. I want replace 2 last methods with another one with same first parameter and second should be lambda operation plusSecondsOperation or minusSecondsOperations. But I do not know how to do it in Java (Java 8).

You can add an argument of type:

BiFunction<LocalDateTime, Integer, LocalDateTime>

To your function that will reflect your need: LocalDateTime (initial date), offset, LocalDateTime (date that will be returned after applying the function).
The method will look like this:

private void shiftEventDateTime(EventDto event, BiFunction<LocalDateTime, Integer, LocalDateTime> f){}

To apply the function inside the method you can write it this way:

f.apply(event.getStartDateTime(), getOffsetSeconds(event.getStartDateTime(), event.getStartDateTimeZone()));
f.apply(event.getEndDateTime(), getOffsetSeconds(event.getEndDateTime(), event.getEndDateTimeZone()));

And when you invoke your method you need to specify the operation itself:

shiftEventDateTime(event, LocalDateTime::minusSeconds);
shiftEventDateTime(event, LocalDateTime::plusSeconds);

You can choose whatever name for the BiFunction that you like and the one that fits your case the most.


Regular Expressions - finding two or more vowels with a consonant before and after it, includes overlapping Is there a way to make my code more compact or efficient?

Testcase example 1 : rabcdeefgyYhFjkIoomnpOeorteeeeet
output:
ee
Ioo
Oeo
eeeee

Testcase example 2 : baabooteen
output:
aa
oo
ee

import re
def find_two_or_more_vowels(string: str):
    match_obj = list(re.finditer(r'(?<=[qwrtypsdfghjklzxcvbnm])([aeiou]{2,})(?=[qwrtypsdfghjklzxcvbnm])', string, re.IGNORECASE))
    if len(list(match_obj)) != 0:
        for match in match_obj:
            print(match.group())
    else:
        print(-1)

find_two_or_more_vowels(input())

Raw Strings

 r'(?<=[qwrtypsdfghjklzxcvbnm])([aeiou]{2,})(?=[qwrtypsdfghjklzxcvbnm])'

The advantage of raw strings is you don't have to escape (add a \ before) certain characters, such as quotation marks and the backslash character itself.  You aren't using any characters you need to escape here, so why use a raw string?

Redundant lists

match_obj = list(...)
if len(list(match_obj)) != 0:
    ...

match_obj is already a list; you don't need to make a new list out of it, to determine it's length.  Just use match_obj directly:

match_obj = list(...)
if len(match_obj) != 0:
    ...

Of course, a list of length zero is falsy, and any list of non-zero length is truthy, so you don't need the len(...) != 0 test:

match_obj = list(...)
if match_obj:
    ...

list(re.finditer)

The function re.finditer(...) returns an iterator, and avoids building up the complete result, so you can process a string piece by piece, distributing the memory usage over time instead of collecting and returning all results immediately.

Passing the result of re.finditer(...) to list(...) immediately runs the iterator to completion, collecting all results into the in-memory list.  Any efficiency gained by using the iterator version is lost, and may actually decrease performance because the work required to create the iterator, save temporary state, etc., has been wasted.

The only thing you do with the resulting match objects is call .group() on them, to get the matched text.

So why not use re.findall(...) which returns the list of matched strings?

    matches = re.findall(r'(?<=[qwrtypsdfghjklzxcvbnm])([aeiou]{2,})(?=[qwrtypsdfghjklzxcvbnm])', string, re.IGNORECASE))
    if matches:
        for match in matches:
            print(match)
    else:
        print(-1)

Consonants

This isn't going to make the code more compact or efficient, but it might make it more maintainable and readable:

Is "qwrtypsdfghjklzxcvbnm" the complete list of consonants?  Did you forget any?  You've ordered them in QWERTY order, which makes it hard for a reader to verify it.

Sometimes "y" is considered a vowel.  If you were to want to include it, you'd have to add the "y" to the vowel list, and remove it twice from the consonants list.

Maybe you should:

from string import ascii_lowercase

vowels = "aeiou"
consonants = ''.join(set(ascii_lowercase) - set(vowels))

Then you could generate your regex string:

double_vowels = f"(?<=[{consonants}])([{vowels}]{{2,}})(?=[{consonants}])"

and even compile it:

double_vowels = re.compile(
    f"(?<=[{consonants}])([{vowels}]{{2,}})(?=[{consonants}])",
    re.IGNORECASE)

Refactored Code

import re
from string import ascii_lowercase

vowels = "aeiou"
consonants = ''.join(set(ascii_lowercase) - set(vowels))

double_vowels = re.compile(
    f"(?<=[{consonants}])([{vowels}]{{2,}})(?=[{consonants}])",
    re.IGNORECASE)

def find_two_or_more_vowels(string: str) -> None:
    matches = double_vowels.findall(string)
    if matches:
        for match in matches:
            print(match)
    else:
        print(-1)

if __name__ == '__main__':
    find_two_or_more_vowels(input())


Parsing positive integers from CSV file I Needed to parse some positive integers with the following constraints:

If possible use C++ only (no C API)
Needs to be able to process parsed data after each newline
Should be reasonably fast
Memory usage should be kept low  (i.e. don't read the entire file in one go)
CSV file is well formed so error checking can be mostly omitted
Unknown amount of lines in file
Should support both unix (\n) and windows (\r\n) line endings

This code runs fine and is faster than the standard approach of streaming via >>.
On average it takes 290ms to parse 10,000,000 lines whereas the version with >> takes 1.1s which I think is not a bad improvement.

However I have some concerns about this:

Are there any obvious mistakes that make this slower than it should be?
Are there any side effects or undefined behavior?
Is the template part applied correctly or is there a better way to do it?
Does the naming make sense?

Please also point out anything else you notice.

Sample input:

1,22,333
4444,55555,666666

Code:

#include <algorithm>
#include <fstream>
#include <string>
#include <vector>

inline void parse_uints(
        const char* buffer_ptr,
        std::vector<uint_fast16_t>& numbers) {
    bool is_eol = false;
    while (!is_eol) {
        uint_fast16_t parsed_number = 0;
        for (;;) {
            if (*buffer_ptr == ',') {
                break;
            }
            if (*buffer_ptr == '\r' || *buffer_ptr == '\0') {
                is_eol = true;
                break;
            }
            parsed_number = (parsed_number * 10) + (*buffer_ptr++ - '0');
        }
        // skip delimiter
        ++buffer_ptr;
        numbers.emplace_back(parsed_number);
    }
}

template<typename T>
void read_line(
        const std::string& filename,
        const uint_fast8_t& line_length,
        const uint_fast8_t& values_per_line,
        T callback) {
    std::ifstream infile{filename};
    if (!infile.good()) {
        return;
    }

    std::vector<uint_fast16_t> numbers;
    numbers.reserve(values_per_line);

    std::string buffer;
    buffer.reserve(line_length);

    while (infile.good() && std::getline(infile, buffer)) {
        parse_uints(buffer.data(), numbers);
        callback(numbers);
        numbers.clear();
    }
}

int main(int argc, char** argv) {
    constexpr uint_fast8_t line_length = 25;
    constexpr uint_fast8_t values_per_line = 3;
    read_line(argv[1], line_length, values_per_line, [](auto& values) {
        // do something with the values here, for example get the max
        auto max = std::max_element(std::begin(values), std::end(values));
    });
}

Some couple nits.

You function read_line does not what it suggests. It reads a file line by line. So you should find an appropriate name.
Your choice of uint_fast8_t/uint_fast16_t is interesting given that your example csv table hold some larger values. Have you measured the impact vs unsigned int or std::size_t. Be aware that modern cpu can read multiple elements at once so you choice might actually have negative impact.
Every line you clear numbers and build it up again. It will be beneficial to just initialize it once via resize and then just overwrite the old value. That way you can omit the unnecessary clear
Getline takes a third argument which is the delemiter. Also getline stops at newline and end of file so you dont need all that error checking Given that you now the number of entries per line you can simply loop and accumulate

while (infile.good()) {
    for (auto&& elem : numbers) {
        std::getline(infile, buffer, ",");
        elem = 0;
        for (auto&& digit : buffer) {
            elem *= 10;
            elem += (digit - '0');
        }
    }
    callback(numbers);
}

If you want to be sure you can check getline and return if its bad.

    while (infile.good()) {
        for (auto&& elem : numbers) {
            if (!std::getline(infile, buffer, ",")) {
                return;
            }
            elem = 0;
            for (auto&& digit : buffer) {
                elem *= 10;
                elem += (digit - '0');
            }
        }
        callback(numbers);
    }


More Pythonic version of finding substring with one glob-like expression Giving the following example list the task is: find out whether the
  second expression is in the first one. * shall be considered as a
  wildcard for any character and one should be able to escape it \*

  Hello,ell
This is good, is
CodeEval,C*Eval
Old,Young

  should evaluate to

  true
true
true
false

I wrote the following code which solves this problem. However, my solution seems very cumbersome and slow. Do you know how to improve it? (The task is for CodeEval and this solution is actually too slow. The actual solution which succeeded is much shorter but it does not check if the search_exprs are in the right order)

import sys
import re

def all_occ(ss, s):
    """ Finds All Occurences of substring ss in string s and returns
    for each occurence its last index
    """
    start = 0
    while True:
        try:
            start = s.index(ss,start)+len(ss)
        except ValueError:
            break
        yield start

def is_ss(s, ss):
    search_exprs = [x.replace('\*', '*') for x in re.split(r'(?<!\\)\*', ss)]

    # Get the list of all occurences of each search expression
    find_indices = [list(all_occ(sub, s)) for sub in search_exprs]

    # If any of the indices is not found, then the expression does not match
    if not any(find_indices):
        return "false"

    # Check if the expressions are in the right order
    start = 0
    for el in find_indices:
        start = min([e for e in el if e>start])
        if not start:
            return "false"

    return "true"

for line in open(sys.argv[1]).read().splitlines():
    if line:
        print is_ss(*line.split(','))

Here the actual solution that has been accepted by codeeval but would fail if the expressions were in the wrong order:

import sys
import re

def is_ss(s, ss):
    search_exprs = [x.replace('\*', '*') for x in re.split(r'(?<!\\)\*', ss)]

    if any(map(lambda x: x in s, search_exprs)):
        return "true"
    else:
        return "false"

for line in open(sys.argv[1]).read().splitlines():
    if line:
        print is_ss(*line.split(','))

Language interpretation

  Should one be able to escape escapes? –  icktoofay Jun 21 at 23:47

  No, one should not :) –  ProfHase85 Jun 22 at 8:26

I agree with @icktoofay's suggestion.  In the absence of any indication to the contrary, I would assume that any backslash in the globlike expression should cause the following character to be interpreted literally.  That means that \\ (a pair of backslashes) should be interpreted as one literal backslash.

In general, any sane language that has an escaping mechanism must also have a way to let you specify a literal sequence of characters that looks like an escape.  Examples:

String literals in C and Python: \\ is a literal backslash.
printf() format strings: %% produces a literal % character in the output.
HTML and XML: &amp; is a literal &.
LDAP search filters: \5c matches a literal \.

If it were not possible to escape escapes, how would one search for a literal \* (backslash, asterisk) in the text?  Based on norms established by C string literals, I would expect the globlike expression \\\* to accomplish that goal.

With that interpretation,

re.split(r'(?<!\\)\*', ss)

is insufficient for the task. The interpretation should depend on whether there are an even or odd number of backslashes preceding the asterisk.

Search technique

Anything other than a one-pass search is likely doomed to failure.  If you search for literal substrings, you are likely to have problems handling overlapping sequences.  Even if you fix the overlap problem, you would likely still have problems dealing with repeating substrings in the pattern.  If there are multiple wildcards in the pattern, you would also need to support backtracking.

In short, I don't recommend that approach at all.

Driver

   for line in open(sys.argv[1]).read().splitlines():
       if line:
           print is_ss(*line.split(','))

I recommend using fileinput.input() so that the program will read its data from either stdin or a given filename.

Personally, I would also prefer not to read in the entire file at once, for scalability.

I would consider it good practice to limit split() to two elements.  The problem is silent on how a third comma on the line should be interpreted, but I would treat it as a literal character in the globlike expression (even if it will always result in a match failure).

I would also decompose the problem differently.  is_ss(s, ss) (confusingly named function and parameters, by the way) is responsible for interpreting ss as a pattern, performing the match, and returning "true" or "false".  That's actually two or three separate tasks.

Suggested solution

Since matching individual substrings is a problematic strategy, and writing a pattern matcher from scratch seems like it would be tedious, I've chosen to translate globs into regular expressions.  The trick is to escape everything except unescaped asterisks.

As a bonus, obtaining a regular expression converts the task to a solved problem.  The performance characteristics of regular expression matching in Python are well known.  Pushing the responsibility of performing the match to the main loop is also a benefit, in my opinion.

import fileinput
import itertools
import os
import re

def globlike_to_re(expr):
    def unescaped_globlike_to_re(expr):
        '''Convert a globlike expression to a regex pattern.  The expr
        parameter is guaranteed to contain no backslashes, unless it is the
        last character.  Therefore, any asterisk in expr means "match
        anything", and everything else is taken literally.'''
        return r'.*'.join(re.escape(literal) for literal in expr.split('*'))

    # [glob, literal, glob, literal, ..., glob]
    pairs = re.split(r'\\(.)', expr)

    lang = itertools.cycle([unescaped_globlike_to_re, re.escape])
    return re.compile(''.join(interp(expr) for interp, expr in zip(lang, pairs)))

for line in fileinput.input():
    haystack, needle = line.rstrip(os.linesep).split(',', 2)
    print 'true' if globlike_to_re(needle).search(haystack) else 'false'


Debounce function that limits the rate a callback is triggered. Which implementation is better, and why? The Debounce technique allow us to “group” multiple sequential calls in a single one - The debounce() function forces a function to wait a certain amount of time before running again.
I wrote both debounce_1 & debounce_2 functions while solving a programming challenge, they produce the same result but I want to know which implementation is better and why, as I'm currently studying JavaScript to improve the quality of my code.

/* Write a function called 'debounce' that accepts a function and returns a
   new function that only allows invocation of the given function after
   'interval' milliseconds have passed since the last time the returned
   function ran.

   Additional calls to the returned function within the 'interval' time
   should not be invoked or queued, but the timer should still get reset. */

function debounce_1(callback, interval) {
  let lastTime = -Infinity;

  return function(){
    let now = Date.now(), res;

    if (now - lastTime > interval) {
      res = callback();
    }

    lastTime = now;
    return res;
  }
}

function debounce_2(callback, interval) {
  let timeout = null;

  return function(){
    let res;

    if (!timeout) { res = callback(); }

    clearInterval(timeout);
    timeout = setTimeout(() => timeout = null, interval);

    return res;
  }
}

/* TESTING */
function hello() { return 'hello'; }

// UNCOMMENT BELOW TO TRY EITHER ONE:
const sayHello = debounce_1(hello, 3000);
// const sayHello = debounce_2(hello, 3000);

console.log( sayHello() );                                 // -> 'hello'
setTimeout(function() { console.log(sayHello()); }, 2000); // -> undefined
setTimeout(function() { console.log(sayHello()); }, 4000); // -> undefined
setTimeout(function() { console.log(sayHello()); }, 8000); // -> 'hello'

I think the solution with the timeout variable is far more clear, and avoids arithmetic operations. However, your implementation has some odd behaviours. That is, using debounce with a high frequency will postpone the callback indefinitely.
const debounce = (func, interval) => {
    let timeout = null;
    return ()=>{
        if (timeout) return undefined;
        timeout = setTimeout( ()=>timeout=null, interval)
        return func();
    }
}

As an alternative, I propose this. Using this code, the timeout is only set when an actual function call occurs.


Counting permutations without repetitions for a number or a string Can I make the following code faster with minor modifications? It times out on CodeWars website.

'''
Write a function that takes a number or a string and gives back the number of
permutations without repetitions that can generated using all its element
'''

from itertools import permutations
def perms(object):
    string = str(object)
    perm_set = []
    perm_repeated = permutations(string)
    print(perm_repeated)

    perm_list = [''.join(p) for p in permutations(string)]
    for item in perm_list:
        if item not in perm_set:
            perm_set.append(item)
    return len(perm_set)

#print(perms(737)) == 3

One of the best ways to make a program faster is not to compute things that you don't have to. In this question you are asked to compute the number of permutations. But your implementation goes and constructs all the permutations themselves, only to throw them all away again. It would be better to count them directly, via some kind of a mathematical formula.

Let's take a simpler example to show how this might work. Supposing that you knew that the string you are given has no repeated characters, for example ABC. Then the permutations are:

ABC ACB BAC BCA CAB CBA

but we can count them by observing that there are 3 choices for the first letter, 2 for the second, and one for the third, hence the total number of permutations is \$3 × 2 × 1 = 6\$. We call this "3 factorial" and write \$3! = 6\$.

In the actual question, the string might have repetitions. So let's look at a simple example. Suppose we are given the string AABC, with a repeated letter. Let's distinguish the two copies of A (for the moment) by writing one of them as a and generate all \$4! = 4 × 3 × 2 × 1 = 24\$ permutations:

AaBC AaCB ABaC ABCa ACaB ACBa BAaC BACa BCAa CAaB CABa CBAa
aABC aACB aBAC aBCA aCAB aCBA BaAC BaCA BCaA CaAB CaBA CBaA

You'll see that these permutation come in twos: one with A before a (I've put these in the top row) and the other with a before A (in the bottom row). Two is of course the number of permutations of two items: \$2! = 2\$. So if we go back to the situation where A and a are indistinguishable, there are \${4! \over 2!} = {24 \over 2} = 12\$ permutations.

One more example. Suppose the string is AAAB, with one letter repeated three times. Let's distinguish the three copies as before, and generate all \$4 × 3 × 2 × 1 = 24\$ permutations:

AaαB AaBα ABaα BAaα
AαaB AαBa ABαa BAαa
aAαB aABα aBAα BaAα
aαAB aαBA aBαA BaαA
αAaB αABa αBAa BαAa
αaAB αaBA αBaA BαaA

You'll see that these permutations come in columns of six: in each column there's one with A before a before α, one with A before α before a, and so on, for each of the \$3! = 6\$ permutations of Aaα. So if we go back to the situation where all the As are indistinguishable, there are \${4! \over 3!} = {24 \over 6} = 4\$ permutations.

In the general case where you have a string of \$n\$ letters where \$n_1\$ of them are identical, and another \$n_2\$ of them are also identical, and so on, then the number of permutations is the multinomial formula $$ {n! \over n_1!\,n_2!\ldots n_k!}. $$

So that's easy to program, using collections.Counter to count the number of occurrences of each character in the string, and math.factorial to compute the factorials:

from collections import Counter
from math import factorial

def permutation_count(s):
    """Return the number of different permutations of s."""
    s = str(s)
    c = 1
    for i in Counter(s).values():
        c *= factorial(i)
    return factorial(len(s)) // c

And since it doesn't have to construct all the permutations, it can count large numbers of permutations in a fraction of a second:

>>> permutation_count('AAAABBBCCDDEEFFGHIJKLMNOPQRSTUVWXYZ')
4484873249299542070167817420800000000

A quick timing comparison. First, your code from the post:

>>> from timeit import timeit
>>> timeit(lambda:perms('AAABBCDEF'), number=1)
201.83495365083218

Second, the revised code using a set:

>>> timeit(lambda:len(set(permutations('AAABBCDEF'))), number=1)
0.09620095230638981

Third, counting them directly:

>>> timeit(lambda:permutation_count('AAABBCDEF'), number=1)
5.3646042943000793e-05

That's about 54 microseconds, about 3.7 million times faster than the code in the post.


Theme/skin swap... version 2! (CSS-driven) I basically have an AJAX-fetched skin (html/css) that's loaded into a dummy element (id=SkinContainer) when the page is loaded, and then the content of one of its divs (contentdiv) is fetched with another AJAXHTTPRequest.

At any rate, when the page is loaded, the user can click a button to swap the theme/skin. Below is the (working) code for my theme swap, but I'm wondering whether or not it's the best way to do this:

function themeSwap() {
    var oldTheme = themeSelect;
    themeSelect++;
    if (themeSelect>2 || themeSelect<1) {themeSelect=1;}
    $('html').addClass('js');

    var tempContentDiv = document.getElementById("contentdiv");
    var tempContent = tempContentDiv.innerHTML;

    ReplaceJSCSSFile("css/skin" + oldTheme  + ".css", "css/skin" + themeSelect + ".css", "css");
    AJAX_LoadResponseIntoElement("skinContainer", "skin" + themeSelect + ".txt", function() {themeSwapCallback(tempContent)} );
}

function themeSwapCallback (tempContent) {
    initPage();
    document.getElementById("contentdiv").innerHTML = tempContent;
    setCookie("themeSelection",themeSelect,365);
}

What this basically does is stores the innerHTML of contentdiv into the "tempContent" variable, loads the new skin into skinContainer with an AJAX fetch, and then restores the original content by setting contentdiv's innerHTML to "tempContent."

The reason why it has to use an AJAX fetch on top of the CSS swap is because the structure of the elements changes.

Have I finally have this done correctly?  or is this still not perfect? :(

Without having any other information available as to the restrictions of the project, I have to say that I do not like this implementation whatsoever.

The smartest way to go about swapping css "themes" is by ONLY changing class definitions.  There are several ways to do this, but in the case of a "themed" application the most practical approach would be having seperate .css files for each theme.

So for example, given the following HTML:

...and theme-default.css:

.header { background-color: black; height: 200px; width: 100%; }
.logo { background-image: url('/images/logo.jpg'); height: 200px; width: 200px; }

...and theme-red.css:

.header { background-color: red; height: 200px; width: 100%; }
.logo { background-image: url('/images/logo-red.jpg'); height: 200px; width: 200px; }

You would only need to swap out the css URL that is being called, something like this:

$(function(){
    $("#btnChange").click(function() {
        $('link[href="theme-default.css"]').attr('href','theme-red.css');
    });
});


Modeling rainwater collection and cost The following is a function that takes an area as an input and outputs some resulting calculations.

I thought an object was useful for creating multiple instances with different custom properties overwriting the defaults to make comparisons easy.

The getter and the setters are there so when one property is updated the update() is run to make sure all related properties are updated too.

I have a few of these relatively complicated models to turn from excel sheets into javascript functions so any advice on using many variable and interconnected properties or just the overall code would really be helpful.

function Cistern (inArea){
    // Private
    var _this = this,
        _type = 'Cistern';

    this.getType = function(){
        return _type;
    }

    // Public properties
    this.precipitationPerEvent = 0;
    this.totalStorageNeeded =  0;
    this.tankCost = 0;
    this.systemBaseCost = 0;

    // Public Variables & Defaults
    var properties = {
        area: inArea,
        maxRainEvent: 2,
        tankType: 'C',
        primaryUse: 'O',
        buildingStories: 3,
        fixtureNumber: 10,
        maintenanceLevel: 'M'
    }

    this.update = function(){
        var tankCostPerGallon = 0,
            pumpSize = 0,
            pumpCost = 0;
        // Storage Volume
        _this.precipitationPerEvent = Math.ceil(_this.area*(_this.maxRainEvent/12) * 7.48);
        _this.totalStorageNeeded = Math.ceil((_this.precipitationPerEvent / 100)) * 100;
        // Capital Costs
        if (_this.tankType === 'C'){
            tankCostPerGallon = 1.66;
        } else if (_this.tankType === 'P'){
            tankCostPerGallon = 1.43;
        } else if (_this.tankType === 'S'){
            tankCostPerGallon = 2.51;
        } else if (_this.tankType === 'F'){
            tankCostPerGallon = 1.33;
        }
        _this.tankCost = _this.totalStorageNeeded * tankCostPerGallon;
        if (_this.primaryUse === 'I'){
            pumpSize = Math.ceil(((62.4 * (_this.buildingStories * 10) * (_this.fixtureNumber * this.buildingStories * 0.00891))/550)/0.5);
        } else {
            pumpSize = 0.5;
        }
        pumpCost = -100.71 * Math.pow(pumpSize, 2) + 1327.7 * pumpSize - 39.38;
        _this.systemBaseCost = Math.ceil(_this.tankCost + (_this.tankCost * 0.6) + pumpCost);
        if (_this.primaryUse === 'I'){ _this.systemBaseCost += 2250};
    }

    // Build Getters & Setters
    Object.keys(properties).forEach(function (prop) {
        Object.defineProperty(this, prop, {
            // Create a new getter for the property
            get: function () {
                return properties[prop];
            },
            // Create a new setter for the property
            set: function (val) {
                if (properties[prop] != val){
                    properties[prop] = val;
                    this.update();
                }
            }
        })
    }, this);

    this.update();
}

Firstly: There are a lot of magic numbers here. I'd stick those in variables and name them. For instance, I have no idea what 0.00891 is, but it's apparently to do with pump sizes? I guess? It'd also be nice to have them defined in one place. You have things like a general 1.6x cost multiplier, and a 2250 (presumably dollars) extra cost for a certain cistern type. Rather than hunt around in the code to find those if you need to update them (especially if used more than once!), it be nice to have them defined in one place - and labelled. E.g.

var COST_FACTOR = 1.6,
    TYPE_I_EXTRA_COST = 2250,
    // etc.

The names above are not very good, but it's just to illustrate the point.

And like Matt Zeunert said, the single-letter codes are very opaque as well. I'm sure they're some sort of industry code, but still.

For instance, the "primary use" code has quite a dramatic effect on things if it's exactly "I". Don't know why, but since it's a specific case your Cistern objects could perhaps benefit from an is... function (e.g. isForIrigation, or isForIndoorSkatingRink or whatever it is I stands for) that just returns true/false depending on whether primaryUse === "I". That'll make some later calculations much more expressive, because you can say "if the cistern isForIrigation, then...", rather than somewhat cryptically checking if a property happens to be an uppercase i.

Next, your Object.defineProperty usage is overwrought, it seems to me. Rather than recalculate everything whenever something is changed, it'd be easier to just calculate it when requested.

Sure, it mimics Excel quite well; change one cell, and the change ripples out (no water pun intended). But in whatever you're building, you'll be in charge of making those ripples happen. You'll have to ask for the updated values yourself. Sure, they get updated, but you won't see that until you access them. In which case it'd be simpler to just calculate them then.

On another note, the way you use this and _this betrays some confusion. The _this variable isn't necessary; you can use the plain this inside your update function as it refers to the same Cistern instance. In fact you do so by accident in one place already (a line that uses both _this.buildingStories and this.buildingStories in the same expression).

You can also structure your code more as a proper prototype by making update a true prototype method, rather than a property added by the constructor:

function Cistern() {
  // ...
}

Cistern.prototype = {
  update: function () {
    // ...
  }
};

However, as mentioned, I'd go a different route all together. Namely, I'd split update up, and flip the whole thing around: What's now being accessed with getters and setters becomes just plain properties, and what's now plain properties is replaced with getters - and only getters, since they're derived values and thus read-only. That way, your getters are responsible for calculating their value when you call them.

function Cistern (area) {
  this.area = area;
  this.maxRainEvent = 2;
  this.tankType = 'C';
  this.primaryUse = 'O';
  this.buildingStories = 3;
  this.fixtureNumber = 10;
  this.maintenanceLevel = 'M';

  var getters = {
    precipitationPerEvent: function () {
      return Math.ceil(7.48 * this.area * this.maxRainEvent / 12);
    },

    totalStorageNeeded: function () {
      return Math.ceil(this.precipitationPerEvent / 100) * 100;
    },

    tankCostPerGallon: function () {
      return { // this "table" should probably be extracted and put elsewhere
        'C': 1.66,
        'P': 1.43,
        'S': 2.51,
        'F': 1.33
      }[this.tankType];
    },

    tankCost: function () {
      return this.tankCostPerGallon * this.totalStorageNeeded;
    },

    pumpSize: function () {
      if(this.primaryUse !== 'I') {
        return 0.5;
      }

      // I simplified the math here, but the result should be the same
      return Math.ceil(5.5598 * Math.pow(this.buildingStories, 2) * this.fixtureNumber / 225);
    },

    pumpCost: function () {
      return -100.71 * Math.pow(this.pumpSize, 2) + 1327.7 * this.pumpSize - 39.38;
    },

    systemBaseCost: function () {
      var cost = Math.ceil(1.6 * this.tankCost + this.pumpCost);
      return this.primaryUse === 'I' ? cost + 2250 : cost;
    }
  };

  // create getters
  for(var property in getters) {
    Object.defineProperty(this, property, { get: getters[property] });
  }
}

Now you can update the public properties freely, and whenever you need a calculated value like, say, systemBaseCost, it'll be calculated on the fly, doing whatever intermediate calculations it needs along the way.


Find max values of all subarrays of specific length This is one of the coding questions that I subscribe to and I wanted to solve it in Rust. I would really appreciate your feedback for improving this code and writing idiomatic Rust.

  Given an array of integers and a number k, where 1 <= k <= length of the array, compute the maximum values of each subarray of length k.

  For example, given array = [10, 5, 2, 7, 8, 7] and k = 3, we should
  get: [10, 7, 8, 8], since:

10 = max(10, 5, 2)
7 = max(5, 2, 7)
8 = max(2, 7, 8)
8 = max(7, 8, 7)

  Do this in \$O(n)\$ time and \$O(k)\$ space. You can modify the input array
  in-place and you do not need to store the results. You can simply
  print them out as you compute them.

This is my first attempt:
https://gist.github.com/ginghamtaus/236e8a1d75237a47769ca74b23ac45ac

This is my second attempt:
https://gist.github.com/ginghamtaus/6e0003e43e020130c8fd9346c9019522

use std::collections::VecDeque;

fn main() {
    let a = [10, 5, 2, 7, 8, 7];
    let k = 3;
    let mut deque: VecDeque<usize> = VecDeque::new();
    for i in 0..a.len() {
        match deque.front() {
            None => deque.push_back(i),
            Some(_) => {
                let mut done = false;
                while !done {
                    match deque.back() {
                        Some(&x) => {
                            if a[i] > a[x] {
                                deque.pop_back();
                            }
                            else {
                                done = true;
                            }
                        },
                        _ => { done = true; }
                    }
                }
                deque.push_back(i);
            }
        }

        if i + 1 >= k  {
            match deque.front() {
                Some(&x) => {
                    println!("max({:?}) = {}", &a[i+1-k..i+1], a[x]);
                    if x <= (i + 1 - k) {
                        deque.pop_front();
                    }
                },
                _ => ()
            };
        }
    }
}

Run rustfmt. It will automatically tell you such things as:

else blocks in Rust belong on the same line as the closing } and opening {
spaces belong around binary arithmetic operators: &a[i + 1 - k..i + 1].

Run clippy. It will automatically tell you such things as:

You are using match for a single pattern. Use if let instead.

Don't specify types of variables if type inference can handle it.
If you don't care about the value of an Option, use is_some / is_none instead of matching on it.
Both branches end with push_back, that shared logic should be pulled out of the conditional.
If all you care about is if the front of the queue is present, all you really care about is if it is empty.
You can continue to simplify by transofrming that into a while let and using break.
I'd create a function (or an Iterator implementation) to separate the algorithm and the driver.

use std::collections::VecDeque;

fn max_of_subarrays<F>(a: &[i32], k: usize, f: F)
where
    F: Fn(&[i32], i32),
{
    let mut deque = VecDeque::new();

    for i in 0..a.len() {
        while let Some(&x) = deque.back() {
            if a[i] > a[x] {
                deque.pop_back();
            } else {
                break;
            }
        }

        deque.push_back(i);

        if i + 1 >= k {
            if let Some(&x) = deque.front() {
                f(&a[i + 1 - k..i + 1], a[x]);
                if x <= (i + 1 - k) {
                    deque.pop_front();
                }
            }
        }
    }
}

fn main() {
    let a = [10, 5, 2, 7, 8, 7];
    let k = 3;

    max_of_subarrays(&a, k, |sub, max| {
        println!("max({:?}) = {}", sub, max);
    });
}

Truthfully, I wouldn't do any of that unless I had a really good reason. Instead, I'd just use the less efficient algorithm but very concise implementation:

fn main() {
    let a = [10, 5, 2, 7, 8, 7];
    let k = 3;

    for (sub, max) in a.windows(k).flat_map(|sub| sub.iter().max().map(|max| (sub, max))) {
        println!("max({:?}) = {}", sub, max);
    }
}

I didn't take the time to benchmark this, but there's no allocation required here, so I'd expect it to be faster than the better algorithm in certain cases.


Enumerate list with filter criteria Given the following CreditCard object, how would you get a count of unexpired credit cards? What are the pros/cons of using each method? Or is there a better/optimal way?

public class CreditCard
{
    public int Year { get; set; }
    public int Month { get; set; }
    public int Day { get; set; }
}
public class User
{
    public User()
    {
        CreditCards = new List<CreditCard>();
    }

    public List<CreditCard> CreditCards { get; set; }

    public int NumberOfCreditCards
    {
        get
        {
            int count = 0;
            DateTime localDate = DateTime.Now;
            foreach (CreditCard creditCard in CreditCards)
            {
                DateTime expDate = new DateTime(creditCard.Year, creditCard.Month, creditCard.Day);
                if (DateTime.Compare(expDate, localDate) > 0)
                {
                    count++;
                }
            }

            return count;
        }
    }
}

Is LINQ a better performer?

public int NumberOfCreditCards
{
    get
    {
        DateTime localDate = DateTime.Now;
        return CreditCards.Select(creditCard => new DateTime(creditCard.Year, creditCard.Month, creditCard.Day))
            .Count(expDate => DateTime.Compare(expDate, localDate) > 0);
    }
}

I will assume that the CreditCard class is set in stone, otherwise I probably would store a DateTime in it and calculate Year, Month and Day properties based on that value. Or at least add a separate method or property that'd return a DateTime.

With that said, first of all, I wouldn't use DateTime.Compare since there're documented operators for comparing DateTimes (see further here). Using them is certainely more readable, because reading DateTime.Compare(d1, d2) > 0 makes one (at least me) lag for a moment to realize what exactly it means. Personally I like the LINQ variant much more than the loop one, but I don't think that the intermediate Select statement is necessary, because it contains such trivial logic. I think that the most readable variant, that I'd probably put into production code, looks like this:

public int NumberOfCreditCards
{
    get
    {
        DateTime now = DateTime.Now;
        return CreditCards
            .Count(card => new DateTime(card.Year, card.Month, card.Day) > now);
    }
}

More things that I'd change:

It's probably debatable, but I feel that making NumberOfCreditCards a method and renaming it into something more transparent like GetNumberOfActiveCreditCards would make the code cleaner. It depends on current time and doesn't seem (at least to me) to be a logical atribute of the User type (official guidelines).
You should consider defining the public CreditCards property as IReadOnlyCollection<CreditCard>. A List should be exposed only when you expect the client code to modify your collection, otherwise it's better to use a restrictive interface. And IReadOnlyCollection is better than IEnumerable because it clearly states that the property returns a collection that won't be enumerated at runtime (e.g. that it's not a method with yield return;). It's quite a common practice and the reasoning is written by the TS here. But again, this topic is debatable.


Chaining async functions of a module without Promises I know that promises are the current recommended way to go for asynchronous chaining but, every time I use promises, I don't feel as comfortable as I wish. All that "then" statements and managing scopes always look a bit strange for me.
So, this is the way I've been creating modules and chaining functions. I use a simple queue to chain the calls.

In my opinion, the code is more understandable, you don't need "then" statements, you can explicit change context if needed. It looks easier for me.
I would like opinions and improvements suggestions, critics are welcome. Why should I use promise over this?

"use strict";

var pause = function(ms, callback) {
    setTimeout(function() {
        callback();
    }, ms);
};

var temp = {
    prop1: 'This is the temp prop1 property!'
};

var P = function() {
    let queue = [];
    let SCOPE = this;

    this.prop1 = 'Property';

    this.displayProperty = function(property) {
        var me = this;
        queue.push(function() {
            console.log(this[property]);
            me.resolve();
        });
        return this;
    }

    this.setProperty = function(property, data) {
        var me = this;
        queue.push(function() {
            this[property] = data;
            me.resolve();
        });
        return this;
    }

    this.asyncDisplayProperty = function(property, data) {
        var me = this;
        queue.push(function() {
            var scope = this;
            pause(3000, function() {
                console.log(scope[property]);
                me.resolve();
            });
        });
        return this;
    }

    this.resolve = function() {
        let fn = queue.shift();
        if (fn) {
            fn.apply(SCOPE, arguments);
        }
    }

    this.bind = function(s) {
        queue.push(() => {
            SCOPE = s;
            this.resolve();
        });
        return this;
    }

}

var foo = new P();

foo
    .displayProperty('prop1') //"Property"
    .asyncDisplayProperty('prop1') //"Property" after 3s
    .setProperty('prop1', 'changed property')
    .displayProperty('prop1') //"changed property"
    .bind(temp) //change the context
    .asyncDisplayProperty('prop1') //"This is the temp prop1 property!" after 3s
    .setProperty('prop1', 'changed temp property')
    .displayProperty('prop1') //"changed temp property"
    .resolve();

Just for the record, this is the promise version I've been using:

"use strict";

var temp = {
    prop1: 'This is the temp prop1 property!'
};

var P = function() {
    let CONTEXT = this;

    this.prop1 = 'Property';

    this.displayProperty = function(property) {
        var me = CONTEXT;
        return new Promise((resolve, reject) => {
            console.log(me[property]);
            resolve();
        });
    }

    this.setProperty = function(property, data) {
        var me = CONTEXT;
        return new Promise((resolve, reject) => {
            me[property] = data;
            resolve();
        });
    }

    this.asyncDisplayProperty = function(property, data) {
        var me = CONTEXT;
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log(me[property]);
                resolve();
            }, 3000)
        });
    }

    this.bind = function(s) {
        return new Promise((resolve, reject) => {
            CONTEXT = s;
            resolve();
        });
    }
};

var foo = new P();

Promise.resolve()
    .then(() => foo.asyncDisplayProperty('prop1'))
    .then(() => foo.asyncDisplayProperty('prop1'))
    .then(() => foo.setProperty('prop1', 'changed property'))
    .then(() => foo.displayProperty('prop1'))
    .then(() => foo.asyncDisplayProperty('prop1'))
    .then(() => foo.bind(temp))
    .then(() => foo.displayProperty('prop1'))
    .then(() => foo.setProperty('prop1', 'changed temp property'))
    .then(() => foo.displayProperty('prop1'));

You're basically starting to rewriting promises. I think there are pros and cons:

For your solution:

Its a little simpler. I would have created a wrapper function around queue.push to make it clearer and easier to modify. You could also make this into a re-usable base class. Lastly, I'm not sure why you create and refer to me everywhere instead of just referring to SCOPE.
It's your own code so if it doesn't do what you want you can change it.
You don't need to wait/hope someone will implement a feature you need.

For promises:

Promises has more functionality (Promise.all, catch, race) and you can have multiple thens attached to a promise.
Thousand's of people have reviewed the Promise code for bugs.
Other developers will know what promises are but have to learn your code.


Permutation of a string eliminating duplicates This code lists the permutations of the string, and eliminates duplicates if any. I'm looking for code review, best practices, optimizations etc.

I'm also verifying complexity: \$O(n! * n)\$ as time complexity and \$O(n * n)\$ as space complexity, where \$n\$ is length of the input string.

public final class Permutation {

    private Permutation() {
    };

    /**
     * Return permutation of a given string.
     * But, if the string contains duplicate characters, it
     * takes care to eradicate duplicate permutations.
     *
     * @param string    the string whose permutation needs to be found out.
     * @return  a list with permuted values.
     */
    public static List<String> permutation(String string) {
        final List<String> stringPermutations = new ArrayList<String>();
        permute(string, 0, stringPermutations);
        return stringPermutations;
    }

    private static void permute(String s, int currIndex, List<String> stringPermutations) {
        if (currIndex == s.length() - 1) {
            stringPermutations.add(s);
            return;
        }

        // prints the string without permuting characters from currIndex onwards.
        permute(s, currIndex + 1, stringPermutations);

        // prints the strings on permuting the characters from currIndex onwards.
        for (int i = currIndex + 1; i < s.length(); i++) {
            if (s.charAt(currIndex) == s.charAt(i)) continue;
            s = swap(s, currIndex, i);
            permute(s, currIndex + 1, stringPermutations);
        }
    }

    private static String swap(String s, int i, int j) {
        char[] ch = s.toCharArray();
        char tmp = ch[i];
        ch[i] = ch[j];
        ch[j] = tmp;
        return new String(ch);
    }

    public static void main(String[] args) {
        for (String str : permutation("abc")) {
            System.out.println(str);
        }

        System.out.println("------------");

        for (String str : permutation("aabb")) {
            System.out.println(str);
        }
    }
}

Best beginner's code I've seen.  Possibly ever.  Admittedly, I haven't reviewed too many beginner's programmes, but this one was definitely an easy review.
Only style change I'd suggest is to avoid the single-line if (s.charAt(currIndex) == s.charAt(i)) continue;.  It's totally valid, but easy to miss.  At least put the continue on a new line; many people prefer to put it in braces, too.
Since your main() method is obviously a way to test the rest of the code, I'd suggest pulling the loops that are currently in there into a self-documenting method like testPermutation(String arg) and call that from main().
Now that your main method is so simple (it just contains testPermutation("abc"); and testPermutation("aabb");), change it to either

loop over the arguments to main(), so you can call your program like java yourpackage.Permutation abc aabb, or
read strings from stdin until user exits.

To measure time complexity, you can maintain a counter that gets incremented inside swap(), and infer from that result.  I think you'll find that it's much less than n! * n.
Space complexity is the same as time complexity, since you create a new String every time you swap.  Or depending on how you define "space complexity", I suppose it might be n * time complexity, since each time you swap, you create a String of length n.


AES encryption class I am new to encryption and recently wanted to learn more about it. I researched how to do AES Encryption in java and assembled my own Java AES encryption class. I don't know if there are any major security holes, though.

Can someone experienced in Java encryption look at my code and tell me if there are any serious security vulnerabilities that I should know about?

import java.io.ByteArrayOutputStream;
import java.security.SecureRandom;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class AESEncryption {

    private SecureRandom random = new SecureRandom();
    private Base64.Encoder encoder = Base64.getEncoder();
    private Base64.Decoder decoder = Base64.getDecoder();
    private Cipher cipher = null;
    private ByteArrayOutputStream outputStream;

    /**
     * Initializes AES Encryption and sets Cipher transformation
     */
    public AESEncryption(){
        try{
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * Generates a random salt used to generate a key in encrypt()
     *
     * @return The random salt
     */
    public String generateSalt(){
        byte bytes[] = new byte[16];
        random.nextBytes(bytes);
        return new String(bytes);
    }

    private byte[] generateIv(){
        byte bytes[] = new byte[16];
        random.nextBytes(bytes);
        return bytes;
    }

    /**
     * Encrypt the user supplied word
     *
     * @param word The user supplied word
     * @param salt The salt generated by generateSalt()
     * @return The encrypted word with IV appended encoded
     */
    public String encrypt(String word, String salt) throws Exception{

        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        PBEKeySpec spec = new PBEKeySpec("12345asdqwe".toCharArray(), salt.getBytes("UTF-8"), 65536, 128);
        SecretKey secretKey = factory.generateSecret(spec);
        SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

        byte[] ivBytes = this.generateIv();

        cipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(ivBytes));

        byte[] encrypted = cipher.doFinal(word.getBytes("UTF-8"));
        outputStream = new ByteArrayOutputStream();
        outputStream.write(ivBytes);
        outputStream.write(encrypted);
        return encoder.encodeToString(outputStream.toByteArray());
    }

    /**
     * Decrypts the encrypted word with the salt and appended IV used to encrypt the word
     *
     * @param encryptedWord The encrypted word returned from encrypt()
     * @param salt The salt used to encrypt the encrypted word
     * @return The decrypted word
     */
    public String decrypt(String encryptedWord, String salt) throws Exception{

        byte[] decodedBytes = decoder.decode(encryptedWord);

        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        PBEKeySpec spec = new PBEKeySpec("12345asdqwe".toCharArray(), salt.getBytes("UTF-8"), 65536, 128);
        SecretKey secretKey = factory.generateSecret(spec);
        SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");

        cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(decodedBytes, 0, 16));

        return new String(cipher.doFinal(decodedBytes, 16, decodedBytes.length - 16));
    }

}

public class AESEncryption {

Make the class final unless you design for it to have child classes.

    private Cipher cipher = null;
    private ByteArrayOutputStream outputStream;

Cipher is a stateful object. It should not be used as a field. Imagine sharing an object instance between multiple threads or methods. Try and never assign null (if only because Java will do it itself).

outputStream is only necessary locally. Again, a stateful object, while there is otherwise no message specific state.

            e.printStackTrace();

Never ever do this. Use a // TODO tagging comment and then throw IllegalStateException(e); even configure your IDE to to this by default. Don't keep running with illegal state (and behold, if you do this, you can even make cipher final - which would have been useful if you'd needed it anyway).

        return new String(bytes);

Don't even convert random bytes to a string. Furthermore, if you decode bytes to a string, explicitly identify the encoding. You may lose data if you find invalid bytes (.e.g. anything above 0x7F for UTF-8).

        PBEKeySpec spec = new PBEKeySpec("12345asdqwe".toCharArray(), salt.getBytes("UTF-8"), 65536, 128);

Don't use static password values stuck in source code. Why do I even have to explain this? Note by the way that the reason that the password is a character array is to make it easier to destroy the password when it is not required any more. Beware that Java only uses the lowest 8 bits of each character - better check that you don't accept passwords that contain other values!

The 65537 value is a magic value, and should be constant. But generally you want to use a much higher value nowadays - unless your password is really complex. Making such a value configurable is very important. This however also means that you will have to indicate the value for the ciphertext somehow.

All in all, you are using stringified input / output and you simply throw Exception - which is simply telling your user to be screwed upon any error. Please look at my answer on how to use security exceptions on StackOverflow.

You don't specify any protocol that you are using. The user will have to guess the encodings of what you return. There is no warning of the mode, the inclusion of the IV or that the salt needs to be saved, the iteration count, the character encoding or the base-64 encoding.

You use CBC, which is not an authenticated mode such as GCM.

The salt is random, which means that the key is random. Since you don't include the salt, nobody will ever be able to decrypt. If the salt is saved otherwise, then it will probably get mangled because you forgot to base 64 encode it.

The key derivation is simply copied for the encrypt and decrypt methods. Why wasn't this put into a separate method?

And "mum's the word" apparently - this code seems to encrypt any strings, not just words?

Let's finish with a positive note: you do always perform UTF-8 encoding / decoding on the "word". Base 64 is not wrong either if a text interface is assumed. That's nice!


Dynamically create object I am developing a web-application and I am encountering some trouble :
I have some tabs and each one contains input forms with different values. I need to switch beetween these tabs and see the different contents of each one.
So I thought I could create objects for every tab , but I have to name them , I use something like this :

Object

var step = function(params){
this.id = randID();
this.titolo = null;
this.descrizione = null;
this.dmax = null;
$.extend(this,params);
// this.render();
}

When the button is clicked , it instance a new object

$("#btn").on('click',function(){
stepA = new step({
"titolo" : $("#titolo").val(),
"descrizione" : $("#descrizione").val()
})
var id = stepA.id;
var nome = "step"+id;
console.log(nome);
nome = stepA;
console.log(nome);
});

As you can see , I used this solution to name every step object with his ID

var id = stepA.id;
var nome = "step"+id;
console.log(nome);
nome = stepA;
console.log(nome);

otherwise I think is a really bad solution. Notice that I will call every object by his id clicking on the tabs.

Hope you can help me improve it, thank you guys.

I would use some MV* library for this kind of task.
Maybe you have a look at Backbone. A small library (about 7k in production) with lots of nice functionality for those kinds of tasks.

1) You have models representing you data as a proper javascript object.
Each model is instantiated with:

var MyModel = Backbone.Model.extend({});
var instance = new MyModel();

You could use defaults:

var MyModel = Backbone.Model.extend({
    defaults: { name: 'Freddy Krueger', age: 0, child: '' }
});

Models have events to which you could subscribe. Most used is the "change" event. So you could bind a function to a general change by just declaring

model.on("change", function(){});

Or if you want to watch a specific attribute to change

model.on("change:name", function(){});

Of course you could "trigger" custom events

model.trigger("outOfOrder");

2) You could use views to render the different forms

View = Backbone.View.extend({
    el: $("#placeToRender"),
    render:function(){
        $(this.el).html(yourMagicHTML);
    }
});

Even better: you have microtemplating on board, which means:
You could define HTML including placeholders within a script-tag

<script type="text/template" id="#maintemplate">
    <div>
       <%= content %>
    </div>
</script>

That wouldn't be rendered by your browser, but you could get its content by

$("#maintemplate").html()

So that your view could render itself easily with:

View = Backbone.View.extend({
    el: $("#main"),
    template:_template($("#maintemplate").html()),
    render:function(){
        $(this.el).html(template(this.model.toJSON()));
    }
});

Where

this.model.toJSON()

is in fact a model with a key called "content" (e.g. {content:"blah!"}), which is used to render the template,

so that <%= content %> is substituted with the actual content.
And many more stuff to discover.

Referring to your problem - you could abstract your problem with backbone like the following:
Every tab you need to display is a view to which belongs a template to determine its html as well as a model, which represents the content of the tab.
You could embed each tab in another view, such that you have one embracing view to control the whole tabbing system and nesting views, which represent each individual tab.

You could write a custom show() method to show an individual tab and a method which coordinates which of the tabs is shown and which should be hidden.

So instead of doing the annoying work yourself, it may be a good idea to use a library to help.

Some places to start (besides the official API and documentation):

http://backbonetutorials.com/

http://ricostacruz.com/backbone-patterns/

http://coenraets.org/blog/2011/12/backbone-js-wine-cellar-tutorial-part-1-getting-started/

http://addyosmani.github.io/backbone-fundamentals/


Populating a class whose data is stored in an external application Im currently working on a system that will communicate with other systems via webservice (or some sort of communication). I have a system that stores all user data already and don't want to duplicate data in this new system so I have come up with a way of accessing the data when needed.

In my current system I am planning to just store the user ID from the user system and fetch the data when required. My question is, is the following code considered acceptable/understood or would you suggest an alternative way of achieving this?

public class Person
{
    private string id;
    [Transient]
    private string name;
    [Transient]
    private bool isPopulated;

    public Person(string id){
       this.id = id;
    }

    public string Id{get;set;}

    public string Name{
        get{
            init();
            return this.name;
        }
        set{
            this.name = value;
        }
    }

    private void init(){
        if(!isPopulated){
            TempPerson tempPerson = UserService.getPerson(this.id);
            this.name = tempPerson.Name;
            this.isPopulated = true;
        }
    }
}

Is there a better way to do this and are there any problem with this way?

What you have implemented is a sort of Active Record where the record itself knows how to communicate with the storage.

What is bad about your design is that this kind of code will be extremely hard to unit test. Imagine that you need to write a unit test for a class that uses Person objects. How can you prevent it from calling UserService?

The proper solution for your problem depends on use cases.

Will you need to update your entities and propagate those changes back to server?
Can you load several entities at once using methods other than UserService.getPerson(this.id);?
What is the lifetime of the entities loaded?

Generally the most flexible solution (as I see it) would be to implement a repository and unit-of-work pattern (similar to ISession in NHibernate or DbContext in Entity Framework). Basically it's better not to hide communication with 3rd-party but rather expose it in such a way that you have maximum control and flexibility.

Primitive implementation may look like:

public class Person
{
    public string Id { get; set; }

    public string Name { get; set; }
}

public interface ISessionFactory
{
    IUserServiceSession CreateSession();
}

public interface IUserServiceSession
{
    Person GetPerson(string id);
}

public class SessionFactory : ISessionFactory
{
    public IUserServiceSession CreateSession()
    {
        UserService userService = new UserService(); //better use dependency injection, or cache it once if it's thread-safe.
        return new UserServiceSession(userService);
    }
}

public class UserServiceSession : IUserServiceSession
{
    private readonly Dictionary<string, Person> _cache = new Dictionary<string, Person>();
    private readonly UserService _userService;

    public UserServiceSession(UserService userService)
    {
        _userService = userService;
    }

    public Person GetPerson(string id)
    {
        Person result;
        if (!_cache.TryGetValue(id, out result))
            result = _cache[id] = _userService.getPerson(id);

        return result;
    }
}


Assigning neighbor in a binary tree This code is to solve the problem as mentioned here:

private void assignNeighbors(Node n){
      ArrayList<Node> current = new ArrayList<BinaryTree.Node>();
      if(n!=null) current.add(n);
      while(!current.isEmpty()){
          ArrayList<Node> parents = current;
          current = new ArrayList<BinaryTree.Node>();
          for(Node parent: parents){
              if(parent.left!=null && parent.right!=null){
                  parent.left.neighbor = parent.right;
              }
              if(parent.left!=null)current.add(parent.left);
              if(parent.right!=null) current.add(parent.right);
          }
      }
  }

Expected output is basically: Node:Neighbor

Node class:

public class Node{
        Node left,right;
        Node parent,neighbor; //parent is for some other problems I am solving. It's not related to this question.
        int data;

        Node(int d){
            left = null;
            right = null;
            parent = null;
            data = d;
            neighbor = null;
        }
    }

Make Node generic

The problem description uses node values like A, B, C, ..., yet your Node class can only store int values. There's no need to choose, you can make Node generic:

class Node<T> {
    Node<T> left, right;
    Node<T> neighbor;
    T data;

    Node(T d) {
        left = null;
        right = null;
        data = d;
        neighbor = null;
    }
}

Bug

This implementation doesn't work for the given example data:

        A
     /     \
    B       C
 /    \      \
D      E       F

The neighbor of E should be F, but this implementation will give null.
This is because the only place you set the neighbor is this code:

if (parent.left != null && parent.right != null) {
    parent.left.neighbor = parent.right;
}

This only works for nodes in left position. It doesn't for nodes in right position that have a neighbor.

But you're not too far off. With a few simple changes to the main loop, this can work:

        Node<T> prev = null;
        for (Node<T> node : parents) {
            if (node.left != null) {
                current.add(node.left);
            }
            if (node.right != null) {
                current.add(node.right);
            }
            if (prev != null) {
                prev.neighbor = node;
            }
            prev = node;
        }

Initializing generic types

There are several issues here:

ArrayList<Node> current = new ArrayList<BinaryTree.Node>();

The type of left-hand size is ArrayList<Node> but the right-hand side is ArrayList<BinaryTree.Node>. This only compiles if Node and BinaryTree.Node are the same class. But if they are the same class, then it would be better to refer to them the same way consistently.

...except you don't actually need to specify the generic type of the right-hand side, you can use the diamond operator <> and let the compiler figure out the correct type:

ArrayList<Node> current = new ArrayList<>();

Lastly, it's recommended to declare variables with their interface type rather than the implementation type. So this will be better:

List<Node> current = new ArrayList<>();

Alternative implementation

The current implementation tries to avoid adding null values in the list. The consequence of that is multiple null checks:

Before adding the root
Before adding a left child
Before adding a right child

Instead of having 3 places to check for nulls, you could allow null values in the list, and move the check inside the loop, in one place. Rearranging the code to work that way, the code becomes:

    List<Node<T>> level = new ArrayList<>();
    level.add(root);

    do {
        List<Node<T>> prevLevel = level;
        level = new ArrayList<>();
        Node<T> prevNode = null;
        for (Node<T> current : prevLevel) {
            if (current == null) {
                continue;
            }
            level.add(current.left);
            level.add(current.right);
            if (prevNode != null) {
                prevNode.neighbor = current;
            }
            prevNode = current;
        }
    } while (!level.isEmpty());

I also renamed some variables to slightly more intuitive names.