One Time Pad in Python I'm new to Python, but I really want to get into the swing of doing things the pythonic way. First, does my code follow the pythonic path? Or does it run screaming bloody murder, as it zig-zags through my C++ thought of mind? Probably the latter.

 import sys, random, string
 #import pdb
 #pdb.set_trace()

 def read(name):
     inFile=open(name, 'r')
     content=inFile.read()
     content=list(content.strip())
     return content

 #this function will take a file name and a list of numbers
 #it will convert the nums to chars and write to file
 def write(name, nList):
     outFile=open(name, 'w')
     cList=convertToChar(nList)
     outFile.write(''.join(cList))

 #takes a key length, based on message size and gens rand key
 def gen(keylen):
     i=0
     key=[]
     while i <keylen:
         k=random.SystemRandom()
         k=k.choice(string.printable)
         key.append(k)       #append random letter to key list
         i+=1
     key=convertToNum(key)    #conver the key to numbers for xor later
     write("key.txt", key)
     return key              #for xor'ing later in enc

 #takes a list of chars, converts to nums, and writes to list
 #returns a numList
 def convertToNum(charList):
     numList=[]
     i=0
     for i in charList:
         numList.append(ord(i))
     return numList

 #takes list of nums, converts to chars, and writes to new list
 #retursn the charlist
 def convertToChar(numList):
     charList=[]
     i=0
     for i in numList:
         charList.append(chr(i))
     return charList

 #This will ask the user for a file name
 #converts the
 def enc():
     fileName= raw_input("Please enter a name for your message file")
     #fileName="plaintext.txt"
     plaintext=read(fileName)      #gets a list form of the file
     m= convertToNum(plaintext)    #the message in nums
     mLen=len(m)                   #len of message for size of key
     k=gen(mLen)                   #generate the key
     c=[]                          #list to srote the encrypted message
     c= [a^b for a, b in zip(m,k)] #xor's each element in the tuple (m,k)
     write("ciphertext.txt", c)   #writes the xor'ed message to teh cipher

 def dec():
     ciphertext=read("ciphertext.txt")
     key=read("key.txt")
     ciphertext=convertToNum(ciphertext)
     key= convertToNum(key)
     i=0
     decrypted=([a^b for a, b in zip(ciphertext, key)])
     write("decrypted.txt", decrypted)

 def main():
     enc()
     dec()

  main()

Here are some of your functions translated to be more pythonic:

Context managers mean never having to say your closed():

We can recast thse 2 functions (including fixing the bug of not closing the files):

def read(name):
    inFile = open(name, 'r')
    content = inFile.read()
    content = list(content.strip())
    return content

def write(name, nList):
    outFile = open(name, 'w')
    cList = convertToChar(nList)
    outFile.write(''.join(cList))

to:

def read(name):
    with open(name, 'r') as f:
        return f.read().strip()

def write(name, n_list):
    with open(name, 'w') as f:
        f.write(''.join(convertToChar(n_list)))

big key here is using context managers to automatically close the file, and not bothering to assign intermediate results to a variable.

List comprehensions can save a lot of looping boilerplate:

We will trim down:

def gen(keylen):
    i = 0
    key = []
    while i < keylen:
        k = random.SystemRandom()
        k = k.choice(string.printable)
        key.append(k)
        i += 1
    key = convertToNum(key)
    write("key.txt", key)
    return key

def convertToNum(charList):
    numList = []
    i = 0
    for i in charList:
        numList.append(ord(i))
    return numList

def convertToChar(numList):
    charList = []
    i = 0
    for i in numList:
        charList.append(chr(i))
    return charList

To:

def gen(keylen):
    key = convertToNum([random.SystemRandom().choice(string.printable)
                        for k in range(keylen)])
    write("key.txt", key)
    return key

def convertToNum(charList):
    return [ord(i) for i in charList]

def convertToChar(numList):
    return [chr(i) for i in numList]

All three of these functions now make use of list comprehensions to remove 75% of the lines of code.

NOTE

I did not test these changes they were just typed out in the editor.


Potential type-safety issues on object parsing function in DXL I have inherited the maintenance of a DXL script (for IBM Doors).

In this, I came across various examples of stuff that make me scratch my head. Take this example:

int key = 3
print key

Running this in Doors, results in the expected output: 3.

However, in the documentation, we see that key is also the name of a function.

Object o
for o in numberCache do {
    // must cast the key command.
    int i = (int key numberCache)
    print i
}

While even the reference docs are full of examples declaring stuff like string key, Item key and so on, my concern is about safety.

What bad things I can run into, potentially, leaving the code I'm maintaining as is, knowing that it works, despite the fact it contains several functions using key as a variable name?

For instance, I'm really worried about this function right here:

void linkFindObjects(string value, Module m, string key_name, Skip objectList)
{
    Object  o
    string  key, key2, key3
    bool match1 = false
    bool match2 = false
    bool match = false

    for o in m do {
        key = probeAttr_(o, key_name)

        if(key == value)
        {
            put (objectList, o, o)
        }
    }

}

My concern is that in DXL parenthesis are not mandatory: as you can see in the example, casting key(numberCache) can be simplified in key numberCache. When declaring the first three strings, the only thing preventing the whole code to blow up seems to be the comma. Please ignore for now the fact that the code declares a lot of unused stuff. It is as I got it.

Am I worrying too much?

Of course, it's bad mojo to use predefined key words as variable names, and yes, this might bring you into trouble.

About "key": key is only defined for skip lists (perm: _x key (Skip)) and for the internal perm HttpHeaderEntryString_ key (). It is not possible to cast a Skip list to a string, the code Skip sk = create(); string s = "hello " sk "!" will not be valid, so there is almost no danger that the interpreter wants to make a string concatenation when you have the code xx = key sk, even when key is defined as a string variable.

So, in this case, you are more or less safe.string key key2 key3 will give you a plain old syntax error that you can easily detect.


Program that should output nth arrangement of paintings I'm currently practicing for the British informatics olympiad by doing past papers.

I'm on question 3 of the 2015 paper and trying to use recursion to solve it. I'm pretty new to using recursion but I'm not sure what I can do to make my recursive function any more efficient.

The program runs fine for the smaller test numbers but for larger ones my program takes upwards of 5 seconds, when it should take 1 second max.

I don't want you to fix my code for me (this is a past question so doing that is pointless), what I want to know is: where I am going wrong with my recursive function and how I can use recursion or similar problem solving techniques in the future more efficiently.

Any help would be much appreciated as I'm going to be doing the test tomorrow!

import java.util.*;

public class Q3_2015 {

    static ArrayList<String> works = new ArrayList<String>();
    //static ArrayList<String> allWorks = new ArrayList<String>(); //used for question 2
    static int counter = 0;
    static String currentFinishedWork;
    static int a;
    static int b;
    static int c;
    static int d;
    static int n;
    static boolean fullwork;

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        a = scan.nextInt();
        b = scan.nextInt();
        c = scan.nextInt();
        d = scan.nextInt();
        n = scan.nextInt();

        for (int aAmount = 0; aAmount < a; aAmount++) {

            works.add("A");
        }

        for (int bAmount = 0; bAmount < b; bAmount++) {

            works.add("B");
        }

        for (int cAmount = 0; cAmount < c; cAmount++) {

            works.add("C");
        }

        for (int dAmount = 0; dAmount < d; dAmount++) {

            works.add("D");
        }

        //System.out.println(works);

        WorksSolver("");

        //System.out.println(allWorks); //used for question 2
        System.out.println(currentFinishedWork);

    }

    public static void WorksSolver (String currentWork) {//, int aWorksLeft, int bWorksLeft, int cWorksLeft, int dWorksLeft) {

        if (counter == n) {//allWorks.size() == n) { //used for question 2

            //System.out.println("hhee");
            return;
        }

        fullwork = true;

        if (currentWork.length() - currentWork.replaceAll("A", "").length() < a) {

            fullwork = false;
            WorksSolver(currentWork + "A");
        }

        if (currentWork.length() - currentWork.replaceAll("B", "").length() < b) {

            fullwork = false;
            WorksSolver(currentWork + "B");
        }

        if (currentWork.length() - currentWork.replaceAll("C", "").length() < c) {

            fullwork = false;
            WorksSolver(currentWork + "C");
        }

        if (currentWork.length() - currentWork.replaceAll("D", "").length() < d) {

            fullwork = false;
            WorksSolver(currentWork + "D");
        }

        if (fullwork) {

            currentFinishedWork = currentWork;
            counter ++;
            //allWorks.add(currentWork); //used for question 2
        }

        //if (aWorksLeft == 0 && bWorksLeft == 0 && cWorksLeft == 0 && dWorksLeft == 0) {
    //}

    }
}

I have thought of the following algorithm that is NOT recursive at all and thus has linear \$o(n)\$ complexity (n being the total number of works meaning a+b+c+d+e...):

The order of arrangements in the list is alphabetical.  This means that the list will forever begin with arrangements beginning with A and then arrangements beginning with B and so on. So looking at the example list in the question, the first column of letters shows consecutive ranges of letters: AAABBBBBBCCC. You can calculate this "list of first letters" based on the input values of how many artists and how many works for each artist (I will let you figure out the exact formula, its pretty easy). So now you can determine the first letter of the nth arrangement directly from this formula.

Once you have that, it's pretty easy to calculate the rest of the letters by removing the first letter and applying the formula as if the input was one work less.


Implementing EXCEPT functionality for social networking exercise I am taking Stanford's Introduction to Databases Self-Paced online course. I have gone through the videos in the SQL mini-course, and I am having trouble completing the exercises.

The following is the question from the SQL Social-Networking Query Exercises, Question 5:

  For every situation where student A likes student B, but we have no
  information about whom B likes (that is, B does not appear as an ID1
  in the Likes table), return A and B's names and grades.

The database can be found here or download the schema + data.

My answer to this question is as follows:

SELECT H1.name, H1.grade, H2.name, H2.grade
FROM (SELECT * FROM Likes L1
WHERE L1.ID2 NOT IN (SELECT L2.ID1 FROM Likes L2)) F INNER JOIN
Highschooler H1 ON F.ID1 = H1.ID INNER JOIN Highschooler H2 ON F.ID2 =
H2.ID;

I want to avoid using the WHERE L1.ID2 NOT IN... part of the query.

In particular, I'd like to use two result sets.

The first being the entire Likes relation:
SELECT *
FROM Likes L1;

Then I'd like to take the results from the following query:
SELECT L2.ID
FROM Likes L2

And then someone filter the first result set such that it only includes the tuples in result set 1 if L1.ID2 is not in result set 2.

I feel like there's a join or maybe set operator that can do this?

Formatting
Using indentation and line breaks would make your code easier to read. There is no real "standard" so go with what you feel is clearest. I usually go with something that resembles C indentation a bit. Others use a more Java-like indentation. Doesn't matter, as long as it makes it more readable.
SELECT
    H1.name,
    H1.grade,
    H2.name,
    H2.grade
FROM
(
    SELECT *
    FROM Likes L1
    WHERE L1.ID2 NOT IN
    (
        SELECT L2.ID1
        FROM Likes L2
    )
) F
INNER JOIN Highschooler H1
    ON F.ID1 = H1.ID
INNER JOIN Highschooler H2
    ON F.ID2 = H2.ID;

F and other aliases
It's good practice for aliases to get meaningful names. Making the code shorter is all well and good, and in your case doing a self-JOIN they are necessary; but, your subquery being aliased as F doesn't say much about what it represents.

MySQL limitations
There are several things you could do in other RDBMS that MySQL doesn't allow. You could have made a Common Table Expression, declared a Table Variable, and even used EXCEPT; except, none of those are supported by MySQL. I'm afraid, given the tool, this is about as good as it will get. Perhaps someone else will know of a better way. Only other thing I could think of is using a temp table, but that's totally overkill for something simple like this.


Date Detection with Python RegEx its a practice project from "Automate the Boring stuff with Python" book. i am an intermediate level Python programmer and i tried to solve this problem with less code as possible. This code will not take any wrong date into consideration eg: 29-02-2002 will not be selected because 2002 is not a leap year and only leap years have 29th of feb. i did not add code to also detect dates with months written in words, i could do that too but i want to keep things simple for now and i also did not use pyperclip module to detect dates from copied text to clipboard because i dont want to confuse any beginner who also want to learn from watching my code.
I want master programmers to review my code and if their is another way possible to detect dates then please post your solutions. Also i would appreciate any advice and positive criticism, so i know where i am standing right now and what i need to improve. Thanks. Code is as follows:
    import re

    def date_detector(text):
        date_pattern = re.compile('''
        ([12][0-9]|3[0-1]|0?[1-9])             # to detect days from 1 to 31
        ([./-])                                # to detect different separations
        (1[0-2]|0?[1-9])                       # to detect number of months
        ([./-])                                # to detect different seperations
        (2?1?[0-9][0-9][0-9])                  # to detect number of years from 1000-2999 years
         ''', re.VERBOSE)

        days = []
        months = []
        years = []
        dates = []
        for date in date_pattern.findall(text):
            days.append(int(date[0]))
            months.append(int(date[2]))
            years.append(int(date[4]))

        for num in range(len(days)):

        # appending dates in a list that dont need any filtering to detect wrong dates
            if months[num] not in (2, 4, 6, 9, 11):
                dates.append([days[num], months[num], years[num]])

        # detecting those dates with months that have only 30 days
            elif days[num] < 31 and months[num] in (4, 6, 9, 11):
                dates.append([days[num], months[num], years[num]])

        # filtering leap years with Feb months that have 29 days
            elif months[num] == 2 and days[num] == 29:
                if years[num] % 4 == 0:
                    if years[num] % 100 == 0:
                        if years[num] % 400 == 0:
                            dates.append([days[num], months[num], years[num]])
                    else:
                        dates.append([days[num], months[num], years[num]])

        # appending Feb dates that have less than 29 days
            elif months[num] == 2 and days[num] < 29:
                dates.append([days[num], months[num], years[num]])

        if len(dates) > 0:
            for date in dates:
                print(date)

data = '30-06-2012, 31-12-2012, 15-02-2002, 29-02-2004, 29-02-2002, 31-02-2004, 31-06-2012'

date_detector(data)
```

I suggest some minor improvements in the regular expression:

make sure that the same separator is used between day and month and between month and year with a backreference (?P=sep),
replace numbered capture groups with named, and make non-needed groups, if there wer any, non-capturing with ?:. Consequently, finditer and groupdict are used, and the day is obtained from the match with int(date['day']), etc. This will make the code somewhat more human.

More importantly, I suggest that you get rid of days, months and years lists altogether. These data can be stored in dictionaries in dates list and filtered prior to appending to dates.
As a consequence, you won't need a loop over range(len(days)).
The validation conditions can be OR'ed together without losing clarity, and I propose to make it a separate function date_is_valid(day: int, month: int, year: int) -> bool.
Also, the only parametre in date_detector can be made typed: def date_detector(text: str):.
To sum suggested modifications up:
import re

def date_is_valid(day: int, month: int, year: int) -> bool:
    return (month not in (2, 4, 6, 9, 11)   # 31 days in month (Jan, Mar, May, Jul, Aug, Oct, Dec).
    or day < 31 and month in (4, 6, 9, 11)  # 30 days in month (Feb, Apr, Jun, Sep, Nov).
    or month == 2 and day == 29 and year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
                                            # February, 29th in a Gregorian leap year.
    or month == 2 and day < 29)             # February, 1st-28th.

def date_detector(text: str):
    date_pattern = re.compile('''
    (?P<day>[12][0-9]|3[0-1]|0?[1-9])   # to detect days from 1 to 31
    (?P<sep>[./-])                      # to detect different separations
    (?P<month>1[0-2]|0?[1-9])           # to detect number of months
    (?P=sep)                            # to detect different seperations
    (?P<year>2?1?[0-9][0-9][0-9])       # to detect number of years from 1000-2999 years
     ''', re.VERBOSE)

    dates = []
    for match in date_pattern.finditer(text):
        date = match.groupdict()                            # convert Match object to dictionary.
        del date['sep']                                     # we don't need the separator any more.
        date = {key: int(val) for key, val in date.items()} # apply int() to all items.

        if date_is_valid(date['day'], date['month'], date['year']):
            dates.append(date)

    if len(dates) > 0:
        for date in dates:
            print(date)

data = '30-06-2012, 31-12-2012, 15-02-2002, 29-02-2004, 29-02-2002, 31-02-2004, 31-06-2012'

date_detector(data)
```


combinations of an integer list with product limit In python the itertools module is a good tool to generate combinations of elements. In this case I want to generate all combinations (without repetition) having a subsets of specified length but also with a product limit. For example, given a list of integer numbers I want all subsets of length 4 which product is bellow a given numerical limit, like bellow:
import functools, operator
LST = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31 ]
prod = lambda A : functools.reduce(operator.mul, A )

def combinations_with_limit( LST, length,lim ) :
''':Description: LST - array of integers,
    length = number of elements in each subset ,
    lim = product limit of each subset '''

    H = list(range(length))         # H - represents the index array
    B = [ LST[ii] for ii in H ]     # B - the main array with elements
    while H[0] <= len(LST)-length  :
        for i in range( H[-1], len(LST)) :
            H = H[:-1] + [i]
            B = [ LST[ii] for ii in H ]
            if prod(B) > lim :      ###  LIMIT THE OUTCOME PART . It skips the rest of the iteration
                H[-1] = len(LST) - 1
            elif prod(B) <= lim :
                yield B
            if H[-1] == len(LST) - 1 :    # We reset the index array here
                j = len(H)-1
                while H[j] == len(LST)-length+j :
                    j -=1
                H[j] +=1
                for l in range(j+1, len(H)) :
                    H[l] = H[l-1] +1

for i in combinations_with_limit(LST, 4 , 1000 ) :
    print(i ,end='  ' )

The output will look as follows:
[2, 3, 5, 7]  [2, 3, 5, 11]  [2, 3, 5, 13]  [2, 3, 5, 17]  [2, 3, 5, 19]
[2, 3, 5, 23]  [2, 3, 5, 29]  [2, 3, 5, 31]  [2, 3, 7, 11]  [2, 3, 7, 13]
[2, 3, 7, 17]  [2, 3, 7, 19]  [2, 3, 7, 23]  [2, 5, 7, 11]  [2, 5, 7, 13]

And this is correct. All the products subsets are bellow the requested limit. However, I think that the above code is non-elegant and has some major loop inefficiency as I tested it for larger lists with > thousands of elements.
Do you have any ideas on how to improve it?

Welcome to Python programming!

Your code has various formatting issues, including the fact that when copying it here, you messed up the indentation of the docstring in your function – copying what you write here into my development environment will not work because of that. But let's look at the semantics.

On a high level view, this sounds like a problem I would try to solve recursively.

All the products of one number that are less than or equal to a target (you don't state that equal-to is permitted, but the line if prod(B) > lim : makes me think that is what you want) are exactly the numbers n <= limit, and from there we can generalize to implementing ‘The product of k numbers ≤ p if x is the first number and the product of the remaining k-1 numbers ≤ p//x.’ Note that this works with integer division – If you allow floats or if your limit is exclusive, you need float division.

For that recursive solution, I would use a generator and yield every partial solution up the call chain until I get to the original loop that wants my results.

But let us assume that, for whatever reason, you indeed want a function that solves this iteratively, not recursively.

Then, even before I look at your function, it has issue: 2*3*11*13 = 858 < 1000, but that combination does not appear in your list, so you would do well trying to manually generate maybe two examples where you know the answer, and try to produce them using your function.

If you feel it difficult to use the mental arithmetics, trust the tools you mention:

def combinations_with_limit(lst, length, lim):
    return [x for x in itertools.combinations(lst, length)
            if prod(x) <= lim]

is quite a readable and explicit process. It might throw away a lot of things, but it should help you get test cases.

Once you have a working solution, there are several things in your code to look out for.

Calculating the product separately for various combinations, and even twice in your middle loop, will be expensive. Store it somewhere and manipulate it while moving about, instead of running prod too often, in particular if you have a need to access it twice, like in your if and elif.
You are manipulating both H and B in parallel. That feels dangerous: You need great care to make sure that H goes through all combinations, keeping the right length, and never gains any duplicate elements, and then you add the computational overhead of a full list comprehension on top to generate your Bs. That sounds easy to get wrong, and as your results show, one of the conditions indeed goes wrong.


Encode unicode codepoints to UTF-8 manually I want to encode unicode codepoints to UTF-8 manually. I wrote the following C# code. I tested it with some cases I know, but I would like to know if it's correct for all inputs. I know that Unicode codepoints are undefined beyond 0x10FFFF ,but I don't care about that. Therefore the output of my method might be more than 4 bytes.

private byte[] CodePointToUtf8 (int codepoint)
{
    if (codepoint < 0x80) {
        return new byte[]{
            (byte)(codepoint)
        };
    } else if (codepoint < 0x800) {
        return new byte[]{
            (byte)(0xC0 | (codepoint << 21 >> 27)),
            (byte)(0x80 | (codepoint << 26 >> 26))
        };
    } else if (codepoint < 0x10000) {
        return new byte[] {
            (byte)(0xE0 | (codepoint << 16 >> 28)),
            (byte)(0x80 | (codepoint << 20 >> 26)) ,
            (byte)(0x80 | (codepoint << 26 >> 26))
        };
    } else if (codepoint < 0x200000) {
        return new byte[] {
            (byte)(0xF0 | (codepoint << 11 >> 29)),
            (byte)(0x80 | (codepoint << 14 >> 26)),
            (byte)(0x80 | (codepoint << 20 >> 26)) ,
            (byte)(0x80 | (codepoint << 26 >> 26))
        };
    } else if (codepoint < 0x4000000) {
        return new byte[] {
            (byte)(0xF8 | (codepoint << 6 >> 30)),
            (byte)(0x80 | (codepoint << 8 >> 26)),
            (byte)(0x80 | (codepoint << 14 >> 26)),
            (byte)(0x80 | (codepoint << 20 >> 26)) ,
            (byte)(0x80 | (codepoint << 26 >> 26))
        };
    } else {
        return new byte[] {
            (byte)(0xFC | (codepoint << 1 >> 31)),
            (byte)(0x80 | (codepoint << 2 >> 26)),
            (byte)(0x80 | (codepoint << 8 >> 26)),
            (byte)(0x80 | (codepoint << 14 >> 26)),
            (byte)(0x80 | (codepoint << 20 >> 26)) ,
            (byte)(0x80 | (codepoint << 26 >> 26))
        };
    }
}

Bonus question: Is there an build in way to do that?

Yes, the code is correct for all valid code points. I was first confused about the double shifts, since I have never seen them before, but they do their job well. Other authors typically do a single >> followed by a bit mask, e.g. (codepoint >> 12) & 0x3F to skip the 12 bits to the right and take the next 6 bits. That way, the numbers can be verified more easily, since they are smaller. Plus, all the 01xxxxxx bytes have the same bitmask.

Your code omits some validity checks:

codepoint could be < 0
codepoint could be between 0xD800 and 0xDFFF

Other than these, it is perfect.

I know for sure that this conversion is built-in into C#, I just don't know where. Try loading a file into a string using the UTF-8 encoding. During that loading, the built-in conversion code gets called.


Horridly Inefficient Project Euler #14 in Python - Collatz Sequences I created this solution a while ago, and have been going back over my problems to try to make them all more efficient. I have been stuck on this one, and have tried a few different ideas. So far, my original code has still been the "quickest" at over 2 minutes.

Here is the problem and original solution I came up with:

  The following iterative sequence is defined for the set of positive integers:

  n → n/2 (n is even) n → 3n + 1 (n is odd)

  Using the rule above and starting with 13, we generate the following
  sequence:

  13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 It can be seen that this
  sequence (starting at 13 and finishing at 1) contains 10 terms.
  Although it has not been proved yet (Collatz Problem), it is thought
  that all starting numbers finish at 1.

  Which starting number, under one million, produces the longest chain?

  NOTE: Once the chain starts the terms are allowed to go above one
  million.

MAX_LENGTH = 0
NUM = 0
SEQ = []

def nextTerm(num):
    if num != 1:
        if num % 2 == 0:
            return num / 2
        else:
            return (3 * num) + 1
    if num == 1:
        return 1

current = 2
SEQ.append(current)

for num in range(1000001):
    while current >= 1:
        if current > 1:
            current = nextTerm(current)
            SEQ.append(current)
        if current == 1:
            SEQ.append(current)
            break

    if len(SEQ) > MAX_LENGTH:
        MAX_LENGTH = len(SEQ)
        NUM = num

    current = num + 1
    SEQ = []

print("The number {} produced the max sequence length of {}.".format(NUM,
                                                                     MAX_LENGTH
                                                                     ))

# The number 837799 produced the max sequence length of 525.
# Time: 143.42219 seconds

The thing with this is, I know that for many, many numbers, it will end up creating another seq with the last 95% of the sequence being the same, if that makes sense. So I tried creating a way to check if it will end up being the same as another sequence created, and if so, instead of calculating the rest of the sequence, just copy the other one that's the same. This obviously uses a lot more memory as I'm holding a list of lists now instead of a single list, but I thought the time would still be shorter. After waiting 5 minutes while it was running, I just gave up. I still think this might be a good way to think about and approach the problem, so here is the code for that thought process:

def next_term(num):
    if num != 1:
        if num % 2 == 0:
            return num / 2
        else:
            return (3 * num) + 1
    if num == 1:
        return 1

current = 2
MAIN_SEQ = []
seq = []
MAX_LENGTH = 0
NUM = 0

for num in range(1000001):
    seq = [2]
    while current >= 1:
        for lst in MAIN_SEQ:
            if current in lst:
                seq.append(item for item in lst[lst.index(current):])
                break
        if current > 1:
            seq.append(current)
            current = next_term(current)
        if current == 1:
            seq.append(1)
            MAIN_SEQ.append(seq)
            break

    if len(seq) > MAX_LENGTH:
        MAX_LENGTH = len(seq)
        NUM = num

    current = num + 1

print("The number {} produced the max sequence length of {}.".format(NUM,
                                                                     MAX_LENGTH
                                                                     ))

I would still consider myself a beginner in Python, so clear explanations for what I'm doing inefficiently are very welcome.

You should use memoization. It can be as simple as:

def next(n):
    if n % 2 == 0:
        return n // 2
    else:
        return 3 * n + 1

lengths = {}  # n -> length of sequence starting from n
lengths[1] = 1

def length(n):
    if not n in lengths:
        lengths[n] = 1 + length(next(n))
    return lengths[n]

max = 0
for n in range(1,1000000):
    l = length(n)
    if l>max:
        max = l
        print n, max


Restructuring multiple variables into an array I'm using Groovy to grab properties from a page and each of the properties are grouped into a specific type:

Groovy:

String headerImage = null
String sidebarImage = null
String footerImage = null

String mainVideo = null
String sidebarVideo = null
String overviewVideo = null

//Images
headerImage = properties["headerImage"]
sidebarImage = properties["sidebarImage"]
footerImage = properties["footerImage"]

//Videos
mainVideo = properties["mainVideo"]
sidebarVideo = properties["sidebarVideo"]
overviewImage = properties["overviewImage"]

I'm then outputting those values into my jQuery plugin with JSTL like below. Is there a better way to output the values into a jQuery plugin maybe by grouping them into an array or something? Also I only added three in this example in reality I have about 10 in each section so you can image how ugly that looks when I'm putting those values in my jQuery plugin.

$(document).ready(function () {
    $('.mediaGallery').mediaFilters({
        images: '${headerImage},${sidebarImage},${footerImage}',
        videos: '${mainVideo},${sidebarVideo},${overviewImage}',
    });
});

I don't quite understand why you are using individual variables for the various items since all you are doing is outputting them as a group. It would be much cleaner to collect them into a collection. Perhaps something like this:

//Images
List images = [
  properties["headerImage"],
  properties["sidebarImage"],
  properties["footerImage"]
]

//Videos
List videos = [
  properties["mainVideo"],
  properties["sidebarVideo"],
  properties["overviewImage"]
]

With the output looking like this:

$(document).ready(function () {
    $('.mediaGallery').mediaFilters({
        images: '${images.join(",")}',
        videos: '${videos.join(",")}',
    });
});

That improves readability, and with the example you have given doesn't impact functionality.


OpenVPN Login Bash Shell script for DD-WRT router This script is made to run on DD-WRT as I am running an OpenVPN server on it just to securely connect to my home network when I'm on the go. Basically, the input ($1) that goes into this script is a .tmp file generated by OpenVPN when some user wishes to log into the server. The .tmp file consists of 2 lines where the 1st line is the username and the 2nd line is the password.

In this day and age, I'm afraid that potential hackers could inject unintended malicious arguments into the username or password which could exploit my script with the intention to take control over the DD-WRT router (in a way similar to SQL-Injection). So far I have made some huge improvements to the script but I'm not sure if I am finished yet.

#!/bin/sh

#This script was made with OpenVPN via-file in mind

#Location of the Approved Username/Password File
USERS="/somefolder/users"

#Check to see if username and password in the OpenVPN file has any special characters line by line
#Terminate script if special characters are used
while IFS= read -r line
do
    case "$line" in *[!-_a-zA-Z0-9]*) exit 1 ;; esac
done < "$1"

Username=`awk 'NR==1' "$1"`
Password=`awk 'NR==2' "$1"`

        HASHPASS=`echo -n "$Username$Password" | md5sum | sed s'/\  -//'`
        i=0
        while [ $i -lt 10 ]; do
                HASHPASS=`echo -n $HASHPASS$HASHPASS | md5sum | sed s'/\  -//'`
                i=`expr $i + 1`
        done

    if grep -q "$Username:$HASHPASS" $USERS; then
        echo "User Authenticated."
        exit 0
    fi

echo "Login credentials failed."
exit 1

Be paranoid about $PATH
It's a good idea to start this script with
PATH=/usr/bin:/bin

Also consider using full paths for programs.
Get the shell to check some errors
set -e -u

Use lower-case for variables
Upper-case is used for communicating well-known environment variables between programs.  Prefer lower-case for our own internal shell variables, to avoid any conflicts.
Simplify the valid-character checking
The while-do loop could be a simple grep:
if /bin/grep -q '[^-_a-zA-Z0-9]' "$1"
then exit 1
fi

With set -e, that's simply
! /bin/grep -q '[^-_a-zA-Z0-9]' "$1"

To be honest, I'm not convinced this checking is needed, provided we don't pass the username as a regular expression - see "Match exactly" below.
Options to echo are not portable
Consider printf '%s' instead (or, in Bash, <<< redirection)
Consider for instead of while for counted loop
With Bash, we could use an arithmetic for loop.  For standard shell, consider
for i in $(seq 10)
do
     hashpass=$(printf '%s%s' "$hashpass" "$hashpass" | \
                /usr/bin/md5sum | /usr/bin/cut -d' ' -f1)
done

You could instead write a filter function and just put that in the code 10 times (which might work slightly faster, as parts can work in parallel, and built-in read is better than starting a process to remove the filename part of the output):
function hashround() {
    local hash rest
    read hash rest
    printf '%s%s' "$hash" "$hash" | /usr/bin/md5sum
}

hashpass=$(printf '%s%s' "$Username" "$Password" | /usr/bin/md5sum \
           | hashround | hashround | hashround | hashround | hashround \
           | hashround | hashround | hashround | hashround | hashround \
           | /usr/bin/cut -d' ' -f1)

(We could even eliminate that final cut if we agree to use it as ${hashpass%% *} to remove the second field as a shell substitution.)
Match exactly
Instead of passing a regular expression to the final grep, use grep -F, and also match the entire line (-x):
if /bin/grep -Fxq "$Username:$hashpass" "$users"
then
    echo "User Authenticated." >&2
    exit 0
fi

I've also redirected the output to standard error stream, so it doesn't interfere with actual output.


K&R histogram of length of words I am doing exercise 1-13 of K&R. The problem is to print a histogram of the lengths of words in the input. This is the easier problem, printing the histogram with horizontal bars. This is what I came up with. Is there a better way to do this? Are there any bugs?
#include <stdio.h>

#define MAXLEN 10

int main(){
    int c,length;
    int hist[MAXLEN+1];

    length=0;
    for(int i=0;i<MAXLEN+1;i++) hist[i]=0;

    while((c=getchar())!=EOF){
        if((c==' ' || c=='\t' || c=='\n') && length){
            if(length>MAXLEN)
                hist[MAXLEN]++;
            else
                hist[length-1]++;
            length=0;
        }
        else if(c!=' ' && c!='\t' && c!='\n')
            length++;
    }
    //to deal with situations in which input doesn't end in a space or newline or tab
    if(length>MAXLEN)
        hist[MAXLEN]++;
    else if(length)
        hist[length-1]++;

    //printing the histogram horizontally
    putchar('\n');
    for(int i=0;i<MAXLEN;i++){
        printf("%3d|",i+1);
        for(int j=0;j<hist[i];j++) putchar('x');
        putchar('\n');
    }
    printf(">%d|",MAXLEN);
    for(int i=0;i<hist[MAXLEN];i++) putchar('x');
    putchar('\n');
}

Declare and initialize variables in one go
You can initialize a value at the same time you declare it. This even works for structs and arrays. For example:
int main() {
    int c = 0;
    int length = 0;
    int hist[MAXLEN+1] = {0}; // Initializes all elements to 0

    while ((c = getchar()) != EOF) {
        ...

Use isspace()
Instead of manually checking against spaces, tabs and newlines, use isspace() from <ctype.h>.
Split your code into multiple functions
Even for a simple program like this, it is a good exercise to split the code into multiple functions, and reduce the responsibility of each function as much as possible. This way for example, main() could be reduced to:
int main() {
    int hist[MAXLEN + 1] = {0};

    build_histogram(hist, MAXLEN);
    print_histogram(hist, MAXLEN);
}

Then build_histogram() could be written like this:
static void build_histogram(int hist[], size_t hist_size) {
    int c;
    int length = 0;

    while ((c=getchar())!=EOF) {
        if (isspace(c)) {
            add_word(hist, hist_size, length);
            length = 0;
        } else {
            length++;
        }
    }

    add_word(hist, hist_size, length);
}

So its main function is to scan for words. Then add_word() does the actual work of recording the length of a word in the histogram:
static void add_word(int hist[], size_t hist_size, size_t length) {
    if (length > hist_size)
        hist[hist_size]++;
    else if (length)
        hist[length - 1]++;
}

You can use a similar approach for print_histogram().


Date validation with html5 dates This code validates the following:

enddate should not be less than or equal to startdate.
startdate should not be less than or equal to the date today unless document.getElementById("ltype").value == "1".
The maximum gap between startdate and enddate is one year, more than that should cause an error alert.

Please review my code. I think I covered all test cases, but I am extremely new to JavaScript, so this code might have bugs. And is it fine to compare dates as strings? I did this because as far as I know HTML5 date is a string.

// creates a date object then converts it to a string with yyyy-mm-dd format
function dateFormat(date, addyear) { // addyear is boolean, true means add another year to the date
    var dd = date.getDate();
    var mm = date.getMonth()+1;
    var yyyy = date.getFullYear();
    if (addyear) {
        yyyy++;
    }
    if(dd<10) {
        dd='0'+dd;
    }
    if(mm<10) {
        mm='0'+mm;
    }
    return yyyy+'-'+mm+'-'+dd;
}

function date_compare() {
    var today = dateFormat(new Date(),false);
    // from and to are html5 date fields
    var d1=document.getElementById("from").value;
    var d2=document.getElementById("to").value;
    var startdate = dateFormat(new Date(d1),false);
    var enddate = dateFormat(new Date(d2),false);
    var yeardate = dateFormat(new Date(d1),true);
    if (enddate <= startdate || enddate > yeardate) {
        alert("Dates out of range");
        return false;
    }
    if (document.getElementById("ltype").value != "1" && startdate <= today) {
        alert("Error! date goes backwards!");
        return false;
    }
    return true
}

Instead of giving your variables names like dd/mm/yyyy, you should give them names like day, month, year. Other names like d1 or d2. Should have better names.
You need some space between operators. For example, you have this condition in your code: if(dd<10). Stuff like this can be expanded to if(dd < 10). Variable definitions should also not look like this: var x=...;, but rather, var x = ...;.
You should add some more comments, e.g, describe what the functions/code blocks do, and how the processes behind them work.
Finally, just a small nitpicky thing. Both of your functions should be in camelCase. One of them is in underscore_case.


Converting a method to async I have a method that calls a "bridge" for TraderMarketInfo. When info is received, it checks if info IsSet and raises an event. I want to make this method async. C# .NET4.0 VS2012.

Original method:

public void RequestMarketInfo()
{
    TraderMarketInfo marketInfo = bridge.GetMarketInfoAll(Data.Symbol);
    if (marketInfo.IsSet)
        OnMarketInfoUpdated(new MarketInfoUpdateEventArgs(Data.ConnectionId, marketInfo));
}

My attempt to make it async:

public void RequestMarketInfo()
{
    var task = Task<TraderMarketInfo>.Factory.StartNew(() => bridge.GetMarketInfoAll(Data.Symbol));
    task.ContinueWith(t =>
    {
        if (t.Result.IsSet)
            OnMarketInfoUpdated(new MarketInfoUpdateEventArgs(Data.ConnectionId, t.Result));
    });
}

Is it done right?

You need to be very careful when making code like this multithreaded.  Your implementation will compile, and will execute the GetMarketInfoAll() method on another thread, but it may not do what you want.  There are at least two things to consider:

Synchronization:
The lambda function given to ContinueWith can (and often will) be executed on a different thread from the one that called RequestMarketInfo.  The lambda function in your code invokes an event handler, this means that the code inside the event handler may need to synchronize any data it accesses, or you will end up with race conditions and other threading issues.
Thread Affinity:
Similar to the first point, it may be necessary for you to ensure that the event handler is invoked on a certain thread.  If any of the handlers for the OnMarketInfoUpdated event are updating a UI component in Windows Forms, then you will certainly need to perform those updates on the UI thread using Invoke.

You should also note that depending on the type of application you are developing, it may not actually help you to convert this to async.  For example, web applications under heavy load are already using 1 thread per web request, and are often maxed out.  However, I suspect you are using this inside a GUI and are trying to make the UI more responsive while it processes this long running query, in which case converting this to async is a good idea.


Finding the number of longest contiguous increasing subsequences in a given array This is different from classic LIS problem. Here I want number of contiguous longest increasing subsequences!

For example:

INPUT: arr[] = { 3, 6, 10, 8, 11, 17, 16, 100 }
OUTPUT: 2

Explanation: There are 2 longest contiguous subsequences: { 3, 6, 10 } and { 8, 11, 17 }.

Here is a function that I have made to achieve the task. But is there any optimized way instead of this brute force approach?

#define ll long long int
ll longestIncSeq(vector<ll> temp, ll n)
{
    ll count=0,mymax = -1,flag=0,dummy=0;

    while( (flag==0) && (!(temp.empty())) )
    {
        ll max = 1, len = 1, maxIndex = 0;

        for (ll i=1; i<n; i++)
        {
            if (temp[i] > temp[i-1])
                len++;
            else
            {
                if (max < len)
                {
                    max = len;
                    maxIndex = i - max;
                }
                len = 1;
            }
        }
        if (max < len)
        {
            max = len;
            maxIndex = n - max;
        }
        if( max == 1 )
        {
            return count;
        }
        if( (mymax == max) || (dummy==0) )
        {
            count++;
            dummy++;
        }
        else
        {
            flag = 1;
        }
        temp.erase(temp.begin()+maxIndex , temp.begin()+maxIndex+max);

        mymax = max;
        n = temp.size();
    }
    return count;
}

I have no C/C++ compiler at the moment, but the algorithm only needs one loop, the while+flag being a tiny bit too unreadable.

There are two counters:

Finding the maximum length: maxLength

Sequences with next value >= prior value.
Counting the maximum length: maxCount.

length > maxLength reset maxCount to 1
length == maxLength increment maxCount

So (in java):

static int longestIncSeq(int[] arr) {
    int maxCount = 0;
    int maxLength = 0;
    boolean start = true;
    int prior = Integer.MAX_VALUE;
    int length = 0;
    for (int n : arr) {
        if (start || n < prior) {
            if (length > maxLength) {
                maxLength = length;
                maxCount = 1;
            } else if (length == maxLength) {
                ++maxCount;
            }
            length = 0;
            start = false;
        }
        ++length;
        prior = n;
    }
    if (length > maxLength) {
        maxLength = length;
        maxCount = 1;
    } else if (length == maxLength) {
        ++maxCount;
    }
    return maxCount;
}

Complexity O(N).


Checking site uptime with Google Docs I modified Amit Agarwal's script which checks the uptime of one website so that it now checks several sites. The script runs every 5 minutes, however, I kept receiving mails that a site was down and then 5 mins later that it was up again.

I adapted my code to only log a change if it persisted for two checks, like this:

function siteUptimeCheck(url, row) {
    var response, error;
    var status = "status"+row.toString();         // status1, status2..
    if (!ScriptProperties.getProperty(status))
      ScriptProperties.setProperty(status, 200);
    try {                                         // try, catch, else
        var success = true;
        response = UrlFetchApp.fetch(url);
    } catch(error) {
        success = false;
        insertData(status, url, row, error, response.getResponseCode(), "Site down: ");
        return;
    } if(success) {
        insertData(status, url, row, "Up", response.getResponseCode(), "Site up: ");
    }
}

function insertData(status, url, row, error, code, msg) {
      if (ScriptProperties.getProperty(status) == code) {
          return;                                  // Return if there are no changes
      } else if (ScriptProperties.getProperty(status) == 1) {
          sheet.getRange(row,2).setValue(code);
          if (code != 200) {
            //create newdate log entry
            sheet.getRange(row,3).setValue(newdate +" "+ error);
          }
          ScriptProperties.setProperty(status, code);
          MailApp.sendEmail(email, msg, error);
     } else {
          ScriptProperties.setProperty(status, 1);  // Marker for "something changed"
  }
}

Are there better ways of solving this?

There is no // try, catch, else in javascript.

Instead I would do:

var success = false, state = null;
try {
    response = UrlFetchApp.fetch(url);
    success = true;
    error = "Up";
    state = "Site up: ";
} catch(ex) {
    success = false;
    error = ex;
    state = "Site down: ";
}

insertData(status, url, row, error, response.getResponseCode(), state);


Managing a stopwatch mobile app I'm using the following pattern in my mobile app. The code snippet below manages a stopwatch.

Is there a way to simplify the code for better readability and probably getting away from needing to use MyApp.stopwatch. inside it? Somehow in some cases using this instead works, and in some it doesn't.

And what about getting rid of using repeating var settings = MyApp.stopwatch.settings?

(function (MyApp, $, undefined) {

    // Using strict mode to throw exceptions for 'unsafe' actions and coding patterns
    'use strict';

    // Initializes app
    function init() {
        MyApp.stopwatch.init('startStopwatch', 'pauseStopwatch', 'resetStopwatch');
    }

    // Manages the stopwatch
    MyApp.stopwatch = {

        init: function (startButton, pauseButton, resetButton) {
            document.getElementById(startButton).addEventListener('click', MyApp.stopwatch.startTimer, false);
            document.getElementById(pauseButton).addEventListener('click', MyApp.stopwatch.pauseTimer, false);
            document.getElementById(resetButton).addEventListener('click', MyApp.stopwatch.resetTimer, false);

            MyApp.stopwatch.displayTimer();
        },

        settings: {
            timerId: -1,
            interval: 100,
            millis: 0,
            seconds: 0,
            minutes: 0
        },

        displayTimer: function () {
            // ARE THESE REPEATING DECLARATIONS REALLY NEEDED?
            var settings            = MyApp.stopwatch.settings,
                millis              = Math.round(settings.millis / 100).toFixed(0),
                seconds             = settings.seconds,
                minutes             = settings.minutes;

            if (seconds < 10) {
                seconds             = '0' + seconds;
            }
            if (minutes < 10) {
                minutes             = '0' + minutes;
            }
            document.getElementById('stopwatch').innerHTML = minutes + ':' + seconds + ':' + millis;
        },

        updateTimer: function () {
            // ARE THESE REPEATING DECLARATIONS REALLY NEEDED?
            var settings            = MyApp.stopwatch.settings;
            settings.millis         += settings.interval;
            if (settings.millis >= 1000) {
                settings.millis     = 0;
                settings.seconds    += 1;
            }
            if (settings.seconds >= 60) {
                settings.millis     = 0;
                settings.seconds    = 0;
                settings.minutes    += 1;
            }
            MyApp.stopwatch.displayTimer();
        },

        pauseTimer: function () {
            // ARE THESE REPEATING DECLARATIONS REALLY NEEDED?
            var settings    = MyApp.stopwatch.settings;
            window.clearInterval(settings.timerId);
            settings.timerId = -1;
        },

        startTimer: function () {
            // ARE THESE REPEATING DECLARATIONS REALLY NEEDED?
            var settings    = MyApp.stopwatch.settings;
            if (settings.timerId === -1) {
                settings.timerId = window.setInterval(MyApp.stopwatch.updateTimer, settings.interval);
            }
        },

        resetTimer: function () {
            // ARE THESE REPEATING DECLARATIONS REALLY NEEDED?
            var settings    = MyApp.stopwatch.settings;
            MyApp.stopwatch.pauseTimer();
            settings.millis = 0;
            settings.seconds = 0;
            settings.minutes = 0;
            MyApp.stopwatch.displayTimer();
        }

    };

    // PhoneGap, jQuery & device is ready now -> initialize
    $(document).on('deviceready', init);

}(window.MyApp = window.MyApp || {}, jQuery));

This is what I came up with (untested):

I got rid of your settings-stuff, introduced a variable self so there's no interference with this, moved your initialization code to the only place it is (and can ever be) called from, extracted a method for padding and event handler registration and fixed your updateTimer so it works for values > 1000 (it's not fit for negative values, though). I hope you like it...

(function (MyApp, $, undefined) {
    // Using strict mode to throw exceptions for 'unsafe' actions and coding patterns
    'use strict';

    function addClickHandlerToButton(buttonId, handler) {
        document.getElementById(buttonId).addEventListener('click', handler, false);
    }

    function padLeft(number) {
        number = +number;
        return (number < 10 ? '0' : '') + Math.floor(number);
    }

    // Manages the stopwatch
    var stopwatch = (function(){
        var minutes = 0,
            seconds = 0,
            millis = 0,
            interval = 100,
            timerId = -1,
        displayTimer = function () {
            document.getElementById('stopwatch').innerHTML =
                padLeft(minutes) + ':' +
                padLeft(seconds) + ':' +
                Math.floor(millis);
        },

        updateTimer = function () {
            millis += interval;
            if (millis >= 1000) {
                seconds += millis / 1000;
                millis %= 1000;
            }
            if (seconds >= 60) {
                minutes += seconds / 60;
                seconds %= 60;
            }
            displayTimer();
        },

        pauseTimer = function () {
            window.clearInterval(timerId);
            timerId = -1;
        },

        startTimer = function () {
            if (timerId === -1) {
                timerId = window.setInterval(updateTimer, interval);
            }
        },

        resetTimer = function () {
            pauseTimer();
            millis = 0;
            seconds = 0;
            minutes = 0;
            displayTimer();
        };

        return function (startButton, pauseButton, resetButton) {
            addClickHandlerToButton(startButton, startTimer)
            addClickHandlerToButton(pauseButton, pauseTimer)
            addClickHandlerToButton(resetButton, stopTimer)
            displayTimer();
        };
    })();

    // PhoneGap, jQuery & device is ready now -> initialize
    $(document).on('deviceready', function() {
        stopwatch('startStopwatch', 'pauseStopwatch', 'resetStopwatch');
    });

}(window.MyApp = window.MyApp || {}, jQuery));

EDIT 1+2: updated the code to integrate suggestions from the comments by the OP and fix errors.


Payment system migration GitHub

There need to be a software design supporting gradual migration from one payment system (E-xact) to another (Stripe). Credit cards data are stored outside, so I would like to use both systems in parallel for a while to do not make all users to re-enter credit card data.

Here is what I have at the moment in the domain core:

public interface IMainPaymentAdapter : IPaymentAdapter
{
}

public interface IPaymentAdapter : IPaymentService
{
}

public interface IPaymentGateway : IPaymentService
{
}

public interface IPaymentService
{
    Task<BillingId> RegisterAsync(CreditCard card);
    Task ChargeAsync(BillingId id, decimal amount);
}

The idea is that IPaymentService defines API shape, IPaymentAdaptor is about to be implemented for each payment system in use, IPaymentGateway dispatches calls to the right adaptor based on a BillingId and is supposed to be injected into the consuming code:

public abstract class BillingId
{
    public static BillingId Parse(string text)
    {
        var parts = text.Split('/');
        return (BillingId)Activator.CreateInstance(
            typeof(BillingId<>).MakeGenericType(Type.GetType(parts[0])),
            parts[1]);
    }

    protected BillingId(string value) => Value = value;
    public string Value { get; }
    public abstract Type Adapter { get; }
    public override string ToString() =>
        $"{Adapter.AssemblyQualifiedName}/{Value}";
}

public class BillingId<TAdapter> : BillingId
    where TAdapter : IPaymentAdapter
{
    public BillingId(string value) : base(value) { }
    public override Type Adapter => typeof(TAdapter);
}

My gateway looks like this – note that card registration call is always dispatched to the current IMainPaymentAdaptor implementation, while everything else goes to the adaptor that provided the billing id originally:

[Service]
public class PaymentGateway : IPaymentGateway
{
    public PaymentGateway(IServiceProvider provider) => Provider = provider;
    IServiceProvider Provider { get; }

    public async Task<BillingId> RegisterAsync(CreditCard card) =>
        await Adapter().RegisterAsync(card);

    public async Task ChargeAsync(BillingId id, decimal amount) =>
        await Adapter(id).ChargeAsync(id, amount);

    IPaymentAdapter Adapter() => Adapter(typeof(IMainPaymentAdapter));
    IPaymentAdapter Adapter(BillingId id) => Adapter(id.Adapter);
    IPaymentAdapter Adapter(Type type) =>
        (IPaymentAdapter)Provider.GetService(type);
}

Here is what I have in a Stripe adapter assembly:

public interface IStripeAdapter : IMainPaymentAdapter
{
}

[Service]
public class StripeAdapter : IStripeAdapter
{
    StripeClient Client { get; } = new StripeClient();

    public async Task<BillingId> RegisterAsync(CreditCard card) =>
        new BillingId<IStripeAdapter>(await Client.RegisterAsync(card));

    public async Task ChargeAsync(BillingId id, decimal amount) =>
        await Client.Charge(id.Value, amount);
}

Note that E-xact adapter (a decommissioning one) should be based on IPaymentAdaptor, not the IMainPaymentAdapter:

public interface IEXactAdapter : IPaymentAdapter
{
}

What would you say about this design approach? Does it look clean enough?

Here is a simplified version, thanks to this answer.

public interface IMainPaymentProvider : IPaymentProvider
{
}

public interface IPaymentProvider : IPaymentService
{
    string Name { get; }
}

public interface IPaymentGateway : IPaymentService
{
}

public interface IPaymentService
{
    Task<BillingId> RegisterAsync(CreditCard card);
    Task ChargeAsync(BillingId id, decimal amount);
}

Where:

[TypeConverter(typeof(BillingIdTypeConverter))]
[JsonConverter(typeof(BillingIdJsonConverter))]
public class BillingId
{
    public static BillingId Parse(string text) =>
        IsNullOrWhiteSpace(text) ? null :
        text.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries) is string[] p && p.Length == 2
            ? new BillingId(p[0], p[1])
            : throw new FormatException();

    public BillingId(string provider, string value) =>
        (Provider, Value) = (provider, value);

    public string Provider { get; }
    public string Value { get; }

    public override string ToString() =>
        $"{Provider}:{Value}";
}

So payment gateway looks like:

[Service]
public class PaymentGateway : IPaymentGateway
{
    public PaymentGateway(IMainPaymentProvider mainProvider, params IPaymentProvider[] providers) =>
        (MainProvider, Providers) =
        (mainProvider, providers.ToDictionary(p => p.Name));

    IPaymentProvider MainProvider { get; }
    IReadOnlyDictionary<string, IPaymentProvider> Providers { get; }

    public async Task<BillingId> RegisterAsync(CreditCard card) =>
        await MainProvider.RegisterAsync(card);

    public async Task ChargeAsync(BillingId id, decimal amount) =>
        await Providers[id.Provider].ChargeAsync(id, amount);
}

And a sample provider could be:

public interface IStripeProvider : IMainPaymentProvider
{
}

[Service]
public class StripeProvider : IStripeProvider
{
    StripeClient Client { get; } = new StripeClient();

    public string Name => "Stripe";

    public async Task<BillingId> RegisterAsync(CreditCard card) =>
        new BillingId(Name, await Client.RegisterAsync(card));

    public async Task ChargeAsync(BillingId id, decimal amount) =>
        await Client.Charge(id.Value, amount);
}


Hackerrank.com - Sherlock and Anagrams Summary: Given a string find the number of anagramic pairs of substrings of it. e.g 'abba' pairs are [a,a],[b,b],[ab,ba],[abb,bba] so we have 4 pairs.

I'm wondering if anyone can help me improve my code so that it runs faster. My code passes all test cases when running locally, but times out on hackerrank. Any ideas ?

module.exports = (s = '') => {
    let count = 0
    let pairs = []
    for (let wordSize = 1; wordSize < s.length; wordSize++) {
        for (let wordPosition = 0; wordPosition < s.length; wordPosition++) {
            const letters = s.substr(wordPosition, wordSize)
            const wordKeys = letters.split('');
            pairs.push({ letters, keys: wordKeys, wordPosition })
        }
    }
    let pairIndexes = {}
    for (let i = 0; i < pairs.length; i++) {
        const word = pairs[i]
        pairs.forEach((value, index) => {
            if (word.wordPosition !== value.wordPosition && index !== i && value.keys.length === word.keys.length) {
                const wordSorted = word.keys.sort().join('')
                const valueSorted = value.keys.sort().join('')

                if (wordSorted !== valueSorted) return
                if (pairIndexes[wordSorted] === undefined) pairIndexes[wordSorted] = {}
                const pairKeyWord = `${word.wordPosition}-${value.wordPosition}`
                const pairValueWord = `${value.wordPosition}-${word.wordPosition}`
                if (pairIndexes[wordSorted][pairValueWord] === pairKeyWord) return
                pairIndexes[wordSorted][pairKeyWord] = pairValueWord
            }
        })
    }
    //console.log(pairs)
    //console.log(pairIndexes)
    for (const key in pairIndexes) {
        if (pairIndexes.hasOwnProperty(key)) {
            const pairs = pairIndexes[key];
            count += Object.keys(pairs).length
        }
    }
    return count
}

Test cases:

test('A - Given a string return pairs of anagrams', () => {
  const s = 'mom'
  const expected = 2
  const result = anagrams(s)
  expect(result).toBe(expected)
})

test('B - Given a string return pairs of anagrams', () => {
  const s = 'abba'
  const expected = 4
  const result = anagrams(s)
  expect(result).toBe(expected)
})

test('C - Given a string return pairs of anagrams', () => {
  const s = 'abcd'
  const expected = 0
  const result = anagrams(s)
  expect(result).toBe(expected)
})

test('D - Given a string return pairs of anagrams', () => {
  const s = 'ifailuhkqq'
  const expected = 3
  const result = anagrams(s)
  expect(result).toBe(expected)
})

test('E - Given a string return pairs of anagrams', () => {
  const s = 'kkkk'
  const expected = 10
  const result = anagrams(s)
  expect(result).toBe(expected)
})

test('F - Given a string return pairs of anagrams', () => {
  const s = 'cdcd' // c,c d,d cd,cd, cd,dc dc,cd
  const expected = 5
  const result = anagrams(s)
  expect(result).toBe(expected)
})

test('G - Given a string return pairs of anagrams', () => {
  const s = 'ifailuhkqqhucpoltgtyovarjsnrbfpvmupwjjjfiwwhrlkpekxxnebfrwibylcvkfealgonjkzwlyfhhkefuvgndgdnbelgruel'
  const expected = 399
  const result = anagrams(s)
  expect(result).toBe(expected)
})

test('H - Given a string return pairs of anagrams', () => {
  const s = 'gffryqktmwocejbxfidpjfgrrkpowoxwggxaknmltjcpazgtnakcfcogzatyskqjyorcftwxjrtgayvllutrjxpbzggjxbmxpnde'
  const expected = 471
  const result = anagrams(s)
  expect(result).toBe(expected)
})

Your code does indeed run forever. Regrettably you don't describe the method you're using, so I will have to get that from your code.

You start by getting all possible substring, of all possible sizes, out of the given input string and you store those substrings, its letters and position in an array.
You do a full matrix comparison of each array entry. You test if something is an anagram or not. If it is you store it in a second array.
You count what you stored in the second array.

Somewhere along the way you lost me there. Why all the complexity? You started out well, by getting all possible substrings, but after that it became somewhat messy. A full matrix comparison is certainly not needed. I'll explain.

What are we trying to accomplish here? Let's analyse the problem, taking the simply case of 'abba'. The possible substrings are 'a','b','b','a', 'ab','bb','ba' and 'abb','bba'. nine in total, let's number them 1 to 9.

A full matrix comparison would make 9 x 9 = 81 comparisons. But it is obvious that this would compare the same substrings twice. Comparing 2 to 5 is the same as comparing 5 to 2. So we can leave out at least half of these comparisons, cutting the time we need to do this in half. We also don't need to compare two strings of unequal length, so we won't.

So, in the case of 'abba' we have 3 sets we need to compare. For the 1 character set we have to do 6 comparisons, for the 2 character set 3, and for 3 character set 1. That's a total of 10 comparisons where you did 81. This number gets proportionally lower when the size of the input string increases. It is here where we can gain most of our speed.

Finally we get to the comparison itself. Suppose we want to compare 'ab' to 'ba'. By sorting the characters in both strings we can simply compare them. If they are equal that the strings must be an anagram, and must be counted. This is what you do as well.

So now we know what we will need: We need all possible sorted substrings and perform only the needed comparisons.

In basic Javascript code that would look like this:

function sherlockAndAnagrams(s) {
    var anagrams = 0;
    for (var len = 1; len < s.length; len++) {
        var parts = [];
        for (var pos = 0; pos <= s.length - len; pos++) {
            var part = s.substr(pos, len);
            parts.push(part.split('').sort().join(''));
        }
        for (var index1 = 0; index1 < parts.length; index1++) {
            var part1 = parts[index1];
            for (var index2 = index1 + 1; index2 < parts.length; index2++) {
                var part2 = parts[index2];
                if (part1 == part2) anagrams++;
            }
        }
    }
    return anagrams;
}

Notice how the outer loop goes through all the possible lengths of the substring. By working with one length of string, each time, I will never have to compare two differently sized strings.

The way I build the initial array with substrings looks very similar to what you have, but I only store the sorted substrings. That's all that is needed. By sorting the characters in the substring at this stage I save time.

The comparison of the substrings of one length is now quite simple. Notice how index2 starts at index1 + 1, preventing a full matrix comparison of the subset.

And that's it.

So, the major lesson here is to try to reduce the number of comparisons you have to make by first carefully analysing the problem. For an input string of 4 characters you did 81 comparisons, I do 10 (12%). If the input is 16 characters long this goes to 18,225 and 680 (4%), 32 characters gives 277,729 and 5,456 (2%). You can see where that is going. Almost all these coding challenges, for which basic solutions run too long, require such a careful analysis. They don't require fancy programming.


Printing a Binary Tree top-down (column wise) We have a binary tree, suppose like this:

       8
     /   \
    6     10
   / \   /  \
  4   7 9    12
 / \
3   5

We have to print this binary tree in top-down manner - column wise. Note that, 8, 7 & 9 would be considered in same column. So the required output should be:

3
4
6 5
8 7 9
10
12

Currently I've implemented this problem using two maps, and one queue. Here's the method traversal(Node<T> node), which is invoked first time, passing the root node:

public void traverse(Node<T> node) {

    Queue<Node<T>> queue = new LinkedList<>();

    Map<Integer, List<Node<T>>> columnMap = new TreeMap<>();
    Map<Node<T>, Integer> map = new HashMap<>();

    queue.add(node);

    while (!queue.isEmpty()) {

        Node<T> temp = queue.poll();

        if (map.isEmpty()) {
            map.put(temp, 0);
            columnMap.put(0, new ArrayList<Node<T>>(Arrays.asList(temp)));
        }

        int column = map.get(temp);

        if (temp.left() != null) {
            queue.add(temp.left());

            if (columnMap.containsKey(column - 1)) {
                columnMap.get(column - 1).add(temp.left());
            } else {
                columnMap.put(column - 1, new ArrayList<Node<T>>(Arrays.asList(temp.left())));
            }

            map.put(temp.left(), column - 1);
        }

        if (temp.right() != null) {
            queue.add(temp.right());

            if (columnMap.containsKey(column + 1)) {
                columnMap.get(column + 1).add(temp.right());
            } else {
                columnMap.put(column + 1, new ArrayList<Node<T>>(Arrays.asList(temp.right())));
            }

            map.put(temp.right(), column + 1);
        }
    }

    for (Entry<Integer, List<Node<T>>> entry: columnMap.entrySet()) {
        System.out.println("Column - " + entry.getKey() + " : " + entry.getValue());
    }
}

The idea is, starting from root node as column number 0, the left node will have column number -1, and the right node will have column number 1. Then the right node of the left node will again have column number 0. And similarly I proceed till I've exhausted all the nodes. I've used level order traversal for traversing.

The first map - Map<Node<T>, Integer> is used to get the column number for a particular node. I've used this map, so that I can get the column number of a node in O(1) time. For example, starting with root, I put a mapping - <root, 0>, in the map. And then, put an entry in columnMap - <0, root>, specifying there is currently root at column 0. I've used Queue for the purpose of level-order traversal (Well, it can be avoided by using pre-order, post-order or in-order).

Now, I remove the root from queue, and push it's two children. For left child, I've to find the column number based on it's parent (in this case, root). So, I get the column number for root from map. And subtract 1 from it to get column of left. If the column number is already in the columnMap, I just update the existing list of node for that column, else I add a new entry.

I thought of getting it done with just a single map, but I found it more clear.

Is there some better option? Currently, the code looks a bit complex to me. May be it can be improvised? I'm open to a completely different implementation too, provided it is more clear, and space and time efficient.

Using recursion in this instance helps a lot to reduce code duplication. Particularly, in this case, you have different code blocks depending on whether left() or right() are null.

Using recursion you only need one null check, and this removes a big chunk of code.

The queue is only needed for recursion as well, and, it's purpose was hard to figure out... you should have documented it more carefully...

The map variable is also a variable which has a poorly documented purpose... it's hard to tell what variables are on that, and why.

All in all, your suspicions are right that there's a better way to do this.....

Algorithmically it strikes me that a single Map<List<Integer>> is probably the right structure, and that recursion is a better solution.... consider a recursive function:

recurseTraverse(final Node<Integer> node, final Map<Integer, List<Node<Integer>>> columnmap, final int column) {
    if (node == null) {
        return;
    }
    List<Node<Integer>> list = columnmap.get(column);
    if (list == null) {
        list = new ArrayList<Node<Integer>>();
        columnmap.put(column, list);
    }
    list.add(node);
    recurse(node.left(), columnmap, column - 1);
    recurse(node.right(), columnmap, column + 1);

}

Then calling that with a TreeMap<Integer, List<Node<Integer>>> you should be able to get an improved version of your result.

public void traverse(Node<Integer> root) {
    TreeMap<Integer, List<Node<Integer>>> columnMap = new TreeMap<>();

    recurseTraverse(root, columnMap, 0);

    for (Entry<Integer, List<Node<Integer>>> entry: columnMap.entrySet()) {
        System.out.println("Column - " + entry.getKey() + " : " + entry.getValue());
    }
}

Update: It has been pointed out by Fihop that this answer produces the incorrect results. While it correctly puts each node in to the correct column, it adds them in a depth-first order:

  The accepted solution actually does not work. For example:

    1
   / \
  2   3
   \
    4
     \
      5

  it gives:

2
1 4
5 3 => should be 3 5???

The right solution to this problem is to perform a breadth first traversal (traversing each row of the tree at a time), which requires a queue, and recursion is no longer the best, or even a viable, solution.

In re-working this answer, I have also actually run the code (rather than just typing it in to an answer), and I have almost 2 more years of experience on this. So, there are some other things to point out.

First up, this code can now use Java 8, and the computeIfAbsent() Map method.

Next, using static methods that are also generic methods makes the dependence on Node<Integer> become the generic Node<N>. I have still worked the example using Integers, and I have invented what I believe the Node class should be. It's not exactly the way I would write it because the method names left() and right() would probably be named differently. I have also created a rudimentary toString.

Finally, to work the traversal a helper container-class ColumnFind was created to link a node to a column, and allow the temporary storage of the column for when the next level of the tree is traversed.

It pains me that the traversal and the println calls are in the same method, I feel they should be separate, but to keep the code consistent with my earlier answer, I will leave it like that. A Java 8 function passed in to the traversal would be a better solution....

So, here's the traversal code (and it is working in ideone here: http://ideone.com/p8RWmE ).

public static final <N> void traverse(Node<N> root) {

    final TreeMap<Integer, List<Node<N>>> columnMap = new TreeMap<>();
    final Queue<ColumnFind<N>> queue = new LinkedList<>();

    queueChild(0, root, queue);

    while (!queue.isEmpty()) {
        ColumnFind<N> cf = queue.remove();
        int column = cf.column;
        Node<N> node = cf.node;
        columnMap.computeIfAbsent(column, c -> new ArrayList<>()).add(node);
        queueChild(column - 1, node.left(), queue);
        queueChild(column + 1, node.right(), queue);
    }

    for (Entry<Integer, List<Node<N>>> entry: columnMap.entrySet()) {
        System.out.println("Column - " + entry.getKey() + " : " + entry.getValue());
    }
}

private static final <N> void queueChild(int column, Node<N> node,
                 Queue<ColumnFind<N>> queue) {
    if (node == null) {
        return;
    }
    queue.add(new ColumnFind<>(column, node));
}


Code dealing with files and separate lines in them I have been using similar piece of code since a while. I have read some issues regarding treating mapped memory as a string. I am not sure about that though, so I just use strndup(3) to avoid it anyway.

It's often said to use fopen, fwrite and all those f* functions over read(2), write(2) etc. The reason being, these functions handle the reading and writing quite well by intermediate buffering and are quite well organised too. But in my personal opinion, dealing with files with mmap(2) generally tends to be faster, gives nice control over the data because of MAP_* flags and making a structure yourself can organise data pretty well too. These things hold true except in some cases.

I wanted some reviews on this code and this way of working with files:

#include <sys/mman.h>
#include <sys/stat.h>

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct MyFile {
    const char *filename;
    int fd;
    size_t size;
    char *contents;
};

int setup_myfile(const char *filename, struct MyFile *file);
void clean_myfile(struct MyFile file);

int
main(int argc, char *argv[])
{
    if (argc != 2) {
        fprintf(stderr, "usage: %s filename\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    struct MyFile my_file;
    char *contents, *line, *to_free;

    int err = setup_myfile(argv[1], &my_file);

    if (err == -1) {
        fprintf(stderr, "setup_myfile() failed\n");
        exit(EXIT_FAILURE);
    }

    to_free = contents = strndup(my_file.contents, my_file.size);

    if (to_free == NULL) {
        perror("strndup(3)");
        exit(EXIT_FAILURE);
    }

    while ((line = strsep(&contents, "\n")) != NULL) {

        // Print line by line or do anything with line
        printf("%s", line);
    }

    free(to_free);
    clean_myfile(my_file);

    return 0;
}

int
setup_myfile(const char *filename, struct MyFile *file)
{
    struct stat st;

    file->filename = filename;
    file->fd = open(file->filename, O_RDONLY);

    if (file->fd == -1) {
        perror("open(2)");
        return -1;
    }

    if (fstat(file->fd, &st) == -1) {
       perror("fstat(2)");
       return -1;
    }

    file->size = st.st_size;

    file->contents = mmap(NULL, file->size, PROT_READ | PROT_WRITE, MAP_PRIVATE, file->fd, 0);

    if (file->contents == MAP_FAILED) {
        perror("mmap(2)");
        return -1;
    }

    return 0;
}

void
clean_myfile(struct MyFile file)
{
    munmap(file.contents, file.size);
    close(file.fd);
}

the posted code does not cleanly compile!

Compile with warnings enabled, then fix those warnings.

for gcc, at a minimum use:

-Wall -Wextra -Wconversion -pedantic -std=gnu11

Note: other compilers use different options to produce the same results.

in function: setup_myfile()  there are statements like:

return -1;

However, that only gets execution back to the call in main()

setup_myfile(argv[1], &my_file);

Which is ignoring the returned value.  So, when setup_myfile() fails, main() will keep right on executing, as if everything is OK.

Suggest, rather than: return -1;  to use:

exit( EXIT_FAILURE );

which will properly exit the program

regarding:

file->size = st.st_size;

This is performing an implicit conversion from off_t to unsigned long int.  Probably better to declare file->size as an off_t.


Simpler boolean truth table? I'm doing a CodingBat exercise and would like to learn to write code in the most efficient way. On this exercise, I was just wondering if there's a shorter way to write this code.

monkeyTrouble(true, true) → true
monkeyTrouble(false, false) → true
monkeyTrouble(true, false) → false

public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {

  if (aSmile && bSmile) {
      return true;
  }

  if (!aSmile && !bSmile) {
      return true;
  }

  return false;

}

Sometimes it is easy to forget that the simplest logical constructs like boolean are comparable with the == operator, and that, in Java, (false == false) is true.

With this in mind, your code could become:

public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {
    return aSmile == bSmile;
}

It may be easier to see how to get there if you first transform your original code into

public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {
    if ((aSmile && bSmile) || (!aSmile && !bSmile)) {
        return true;
    } else {
        return false;
    }
}

… which could become

public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {
    return (aSmile && bSmile) || (!aSmile && !bSmile);
}

From there, you may come to the realization that "both true or both false" is equivalent to "both the same".

Here is a verification of the output:

public static boolean monkeyTrouble(boolean aSmile, boolean bSmile) {
    return aSmile == bSmile;
}

private static void testTruth(boolean a, boolean b) {
    System.out.printf("monkeyTrouble(%s, %s) = %s\n", a, b, monkeyTrouble(a, b));
}

public static void main(String[] args) {
    testTruth(true, true);
    testTruth(true, false);
    testTruth(false, true);
    testTruth(false, false);
}

This produces:

monkeyTrouble(true, true) = true
monkeyTrouble(true, false) = false
monkeyTrouble(false, true) = false
monkeyTrouble(false, false) = true


Initializing connection to a MySQL database in PHP I wanted to get some feedback on this way of initializing a connection to a MySQL database.

File includes/db.php:

<?php
$config_path = __DIR__ .  '/../config/database.ini';

$db_ini = parse_ini_file($config_path , true);
$db_info['db_host'] = $db_ini['db_data_source_name']['host'];
$db_info['db_user'] = $db_ini['db_general']['user'];
$db_info['db_pass'] = $db_ini['db_general']['password'];
$db_info['db_name'] = $db_ini['db_data_source_name']['dbname'];

foreach($db_info as $key => $value) {
    $upper_key = strtoupper($key);
    if (!defined($upper_key)) {
        define($upper_key, $value);
    }
}

$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);

?>

Is there anything wrong with the file above being included in other php files as needed?

Thank you!

Why the intermediate step of writing values to array? Why not:

define('DB_HOST', $db_ini['db_data_source_name']['host']);
define('DB_USER', $db_ini['db_general']['user']);
// etc.

Be careful with relative path with regards to including in other pieces of code.  If being included by code in another directory (particularly at a different level in directory structure), this may break.  Also, you won't be able to include this file more than once within any given script execution since you are defining constants.

Since you can only include this once per execution, do you really need to define constants at all?

$connection = mysqli_connect(
    $db_ini['db_data_source_name']['host'],
    $db_ini['db_general']['user'],
    $db_ini['db_general']['password'],
    $db_ini['db_data_source_name']['dbname']
);

I am just generally worried about your thinking of including this within other files "as needed".  That tends to make me think that you don't have a good strategy around managing your application dependencies (such as database connection).  Just sprinkling includes/requires throughout your code can really make your code fragile and hard to maintain.  If you really want to take you application coding to another level, I would suggest familiarizing yourself with dependency injection, both in a philosophical sense as well as from a practical standpoint looking at typical PHP libraries that do this (Pimple, PHP-DI, or pretty much any popular framework has some level of dependency injection strategy).

Hopefully your ini file is separate from your codebase (i.e. not under revision control) to where you are storing your DB passwords in your code.  If that is the case, consider taking the next step and have the ini file parsed in a different process such that this particular code is not responsible for reading configuration data from files that should perhaps should just be available in environmental variables.


Checking the validation of a field through the Property mutator method `set` I'm newish to C#, being mainly Java oriented. I have a field _config which needs to be a value from 1 to 8, and I have this code which checks to make sure I can only set _config to 1-8. If the value given for set is "invalid", _config becomes -1.

public int Config {
    get
    {
        return _config;
    }

    set
    {
        if (value > 8 || value < 1)
        {
            _config = -1;
        }
        else
        {
            _config = value;
        }
    }
}
private int _config; // the actual field that the property 'Config' refers to.

This feels really weird to me, but it does what I need it to do. I'm also thinking about having the setter throw an exception instead of setting _config to -1 when given an invalid value. Am I using Properties correctly, or have I completely misunderstood the point of them?

No one has yet addressed the fact that you have chosen the wrong tool for the job.

What does Config represent? It looks like you should have chosen an enum where you chose an int.

public enum ConfigurationType
{
    None = 0,
    Type1 = 1,
    Type2 = 2,
    // etc.
}

You can get what ConfigurationType an int corresponds to quite easily:

ConfigurationType configType = (ConfigurationType)someInteger;

Then, you can validate it more fluidly:

public ConfigurationType Config
{
    get
    {
        return _config;
    }
    set
    {
        if (ConfigurationType.IsDefined(typeof(ConfigurationType), value))
        {
            _config = value;
        }
        else
        {
            throw new InvalidEnumArgumentException($"The specified value must be a valid value of the {nameof(ConfigurationType)} enumeration.");
        }
    }
}
private ConfigurationType _config; // the actual field that the property 'Config' refers to.

If you don't have C#6.0, your exception would be more along the lines of:

throw new InvalidEnumArgumentException(string.Format("The specified value must be a valid value of the {0} enumeration.", ConfigurationType.ToString()));

You should also consider a refactoring of the name Config, it's non-descriptive. There is likely a better name for such a property/field combination. (Had we more context we would likely be able to suggest better names.)


SPOJ - ADDREV (Adding Reversed Numbers) https://www.spoj.com/problems/ADDREV/

My answer to ADDREV challenge on SPOJ (link to the problem given above), written in JAVA, was accepted. However, the timing was 1.23 and memory used was 82M, which doesn't seem impressive/up-to-the-mark.

I'm new to competitive programming and want to know -
a. In what ways can I optimize my code to take up lesser memory and be quicker?
b. Are their any incorrect programming practices that I have unknowingly followed?
c. Which better way is available to solve this problem in Java?

My code:-

import java.util.*;
import java.lang.*;
import java.math.BigInteger;

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Scanner obj = new Scanner(System.in);
        int t = obj.nextInt(); obj.nextLine(); //clears the buffer
        for(int i=1;i<=t;++i)
        {
            Scanner obj1 = new Scanner(obj.nextLine());

            StringBuffer b1 = new StringBuffer(obj1.next());
            StringBuffer b2 = new StringBuffer(obj1.next());

            b1.reverse(); b2.reverse();

            BigInteger i1 = new BigInteger(b1+"");
            BigInteger i2 = new BigInteger(b2+"");
            i1 = i1.add(i2);
            b1 = new StringBuffer(i1.toString());
            b1.reverse();
            String a = new String(b1.toString());

            for(int j=0;;j++) //To remove leading zeroes (if any)
            {
                if(a.charAt(j)!='0')
                {
                    System.out.println(a.substring(j));
                    break;
                }
            }
        }
    }
}

I have some suggestion for you.

Use the java.lang.StringBuilder instead of the older java.lang.StringBuffer

The java.lang.StringBuilder is generally faster than the older java.lang.StringBuffer.

Use the same instance of java.util.Scanner

Move the java.util.Scanner of the loop, you can reuse it. you can use the obj instance and use only this instance.

Reuse the same java.lang.StringBuilder instead of creating a new one each time.

You can reuse the same builder by clearing it with the method java.lang.AbstractStringBuilder#setLength and passing zero to the method; this will prevent the object creation to be put on the stack and use less memory than creating lots of instances of the builder.

Extract similar code to methods.

In your code, you can extract some of the code to methods; this will make the code shorter and easier to read. I suggest that you create a method to read the input and revert it as a String.


Create SQLite backups I have this script for creating SQLite backups, and I was wondering whether you'd have any suggestions on how to improve this. I was thinking that maybe it should create the backup dir if it doesn't exist, but not sure if it's necessarily better.
Besides functionality/performance tips, any styling/formatting tips are also much appreciated.
#!/usr/bin/env python
"""
This script creates a timestamped database backup,
and cleans backups older than a set number of dates

"""

from __future__ import print_function
from __future__ import unicode_literals

import argparse
import sqlite3
import shutil
import time
import os

DESCRIPTION = """
              Create a timestamped SQLite database backup, and
              clean backups older than a defined number of days
              """

# How old a file needs to be in order
# to be considered for being removed
NO_OF_DAYS = 7

def sqlite3_backup(dbfile, backupdir):
    """Create timestamped database copy"""

    if not os.path.isdir(backupdir):
        raise Exception("Backup directory does not exist: {}".format(backupdir))

    backup_file = os.path.join(backupdir, os.path.basename(dbfile) +
                               time.strftime("-%Y%m%d-%H%M%S"))

    connection = sqlite3.connect(dbfile)
    cursor = connection.cursor()

    # Lock database before making a backup
    cursor.execute('begin immediate')
    # Make new backup file
    shutil.copyfile(dbfile, backup_file)
    print ("\nCreating {}...".format(backup_file))
    # Unlock database
    connection.rollback()

def clean_data(backup_dir):
    """Delete files older than NO_OF_DAYS days"""

    print ("\n------------------------------")
    print ("Cleaning up old backups")

    for filename in os.listdir(backup_dir):
        backup_file = os.path.join(backup_dir, filename)
        if os.stat(backup_file).st_ctime < (time.time() - NO_OF_DAYS * 86400):
            if os.path.isfile(backup_file):
                os.remove(backup_file)
                print ("Deleting {}...".format(ibackup_file))

def get_arguments():
    """Parse the commandline arguments from the user"""

    parser = argparse.ArgumentParser(description=DESCRIPTION)
    parser.add_argument('db_file',
                        help='the database file that needs backed up')
    parser.add_argument('backup_dir',
                         help='the directory where the backup'
                              'file should be saved')
    return parser.parse_args()

if __name__ == "__main__":
    args = get_arguments()
    sqlite3_backup(args.db_file, args.backup_dir)
    clean_data(args.backup_dir)

    print ("\nBackup update has been successful.")

Note: Code works in both Python 2 and Python 3.

There's no need to repeat yourself by defining DESCRIPTION (and in fact your strings have gotten out of sync).  Just reuse the program's docstring:

def get_arguments():
    """Parse the commandline arguments from the user"""
    parser = argparse.ArgumentParser(description=__doc__)
    …


Temperature converter in Rust I've just started learning myself Rust. I am practicing with the exercises from the book available on the official website.
Here is my attempt at the temperature converter exercise at the end of chapter 3.
Could you tell me if my approach is correct? Is there something I could have done more efficiently? Is there something I shouldn't do because it's not how Rust is supposed to work?
Thank you!
use std::io;

fn main() {
    println!("Enter a temperature.");

    let mut temperature = String::new();

    io::stdin()
        .read_line(&mut temperature)
        .expect("Failed to read temperature");

    let (value, unit) = temperature.split_at(temperature.len() - 2);

    let value: f32 = match value.trim().parse() {
        Ok(num) => num,
        Err(_) => panic!("{} is not a number", value),
    };
    let unit = unit.trim().to_lowercase();

    print!("The input temperature is: {}", temperature);

    if unit == "c" {
        c_to_f(value);
    } else if unit == "f" {
        f_to_c(value);
    } else {
        println!("Unsupported unit");
    }
}

fn c_to_f(c: f32) {
    output(c * 1.8 + 32.0, "F".to_string());
}

fn f_to_c(f: f32) {
    output((f - 32.0) / 1.8, "C".to_string());
}

fn output(t: f32, u: String) {
    println!("The output temperature is: {}{}", t, u);
}
```

I hope some late help will still be helpful!
I've erred on the side of providing a bit too much feedback, but this may give you a sense of some of the styles and conventions that Rust uses even if they are overkill for this simple program.

Nicely organized code overall, very understandable and clear use of functions.

In function arguments, it's generally cleaner/more efficient/more idiomatic to accept &str instead of String. This is usually confusing for beginners, but &str is read-only string data and String is an owned, dynamically growable string, so basically if you only need read-only, you should use &str. As a rule of thumb, it's a good starting point to just make all function arguments &str and the return value String. Here's output fixed; noticed that this means you don't have to to .to_string() in your other functions:
fn c_to_f(c: f32) {
    output(c * 1.8 + 32.0, "F");
}

fn f_to_c(f: f32) {
    output((f - 32.0) / 1.8, "C");
}

fn output(t: f32, u: &str) {
    println!("The output temperature is: {}{}", t, u);
}

Although it doesn't make a huge difference for a small project like this, another good rule of thumb is to avoid functions with printing behavior; instead functions should return Strings, and only the top-level program (i.e. main function) prints. So let's change fn output again. All we need to do is use format! instead of println! (and print in main):
fn c_to_f(c: f32) -> String {
    output(c * 1.8 + 32.0, "F")
}

fn f_to_c(f: f32) -> String {
    output((f - 32.0) / 1.8, "C")
}

fn output(t: f32, u: &str) -> String {
    format!("The output temperature is: {}{}", t, u)
}

The let value: f32 logic is a bit verbose, the usual function for this is unwrap_or_else:
let value: f32 = value.trim().parse().unwrap_or_else(|_| {
    panic!("{} is not a number", value)
});

In the line let (value, unit) = temperature.split_at(temperature.len() - 2), this use of split_at is considered fragile and mostly discouraged. Remember that in Rust strings are not just sequences of bytes, but valid UTF-8 data where the characters may not correspond to bytes. So this code introduces a silent failure (i.e. one that is not explicitly exposed and dealt with by the application): I tried running your program on input 4  and I got
thread 'main' panicked at 'byte index 5 is not a char boundary; it is inside ''

In fact, there is actually a second similar issue in the same line: when run with an empty input line in release mode, you have integer underflow:
thread 'main' panicked at 'byte index 18446744073709551615 is out of bounds of `
`'

These edge cases do not introduce a bigger problem for your case, but in production code such failures could cause an unexpected crash, or worse, a security vulnerability. So the preference in Rust is always to be explicit about handling errors. You can browse the functions available in the documentation https://doc.rust-lang.org/std/primitive.str.html for some ideas of how to parse strings in general; here the easiest is probably to explicitly check for both errors:
let mid = temperature.len().checked_sub(2).expect("Input string was empty");
if !temperature.is_char_boundary(mid) {
    panic!("Input should end in a single-byte char (the unit)");
}
let (value, unit) = temperature.split_at(mid);

If you only need mutability for a temporary amount of time (as with temperature), it's good practice to declare the variable immutable after that: let temperature = temperature

The last part of main can be reduced a bit by using match instead of if: match unit.as_str() {

Finally, for extensibility it would be great to abstract temperature into an appropriate type; Rust programmers like to leverage static types to make sure they keep for example Celsius and Fahrenheit values separate, without any actual overhead at runtime. Although I won't change your code for this, you would define types like so:
struct Fahrenheit(f64);
struct Celsius(f64);

You could alternatively have a Temperature type if you want a lot of functionality related to temperatures in general:
enum Temperature {
    Fahrenheit(f64),
    Celsius(f64),
}

Then, you would define parsing functions (parse from &str), display functions (convert to String), and so on on those types, rather than including all of this in main.

Here's the final code incorporating all the suggestions except the last one:
use std::io;

fn main() {
    println!("Enter a temperature.");

    let mut temperature = String::new();
    io::stdin()
        .read_line(&mut temperature)
        .expect("Failed to read temperature");
    let temperature = temperature;

    let mid = temperature.len().checked_sub(2).expect("Input string was empty");
    if !temperature.is_char_boundary(mid) {
        panic!("Input should end in a single-byte char (the unit)");
    }
    let (value, unit) = temperature.split_at(mid);

    let value: f32 = value.trim().parse().unwrap_or_else(|_| {
        panic!("{} is not a number", value)
    });
    let unit = unit.trim().to_lowercase();

    println!("The input temperature is: {}", temperature);

    match unit.as_str() {
        "c" => println!("{}", c_to_f(value)),
        "f" => println!("{}", f_to_c(value)),
        _ => panic!("Unsupported unit"),
    }
}

fn c_to_f(c: f32) -> String {
    output(c * 1.8 + 32.0, "F")
}

fn f_to_c(f: f32) -> String {
    output((f - 32.0) / 1.8, "C")
}

fn output(t: f32, u: &str) -> String {
    format!("The output temperature is: {}{}", t, u)
}