Project Euler 23 - Non-Abundant Sums I'm new to Python! Kindly suggest me improvements!

Problem statement :

  A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.

  As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest
  number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.

  Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.

My Work:

import math
dict = {}

def get_divisors_sum(num):
    list  = []
    for i in range(1, int(math.sqrt(num)+1), 1):
        if (num%i==0):
            b = num/i
            if (i==b):
                list.append(i)
            else:
                list.append(i)
                list.append(b)
    return sum(list) - num

# print get_divisors(28)

def generate_abundant_numbers():
    list = []
    for i in range(1, 28123, 1):
        if get_divisors_sum(i) > i:
            list.append(i)
    return list

def insert_to_dictionary():
    global dict
    list = generate_abundant_numbers()
    for i in range(0, len(list) - 1, 1):
        for j in range(i, len(list), 1):
            dict[list[i] + list[j]] = 1
    print dict

def print_answer():
    sum = 0
    for i in range(1, 28123, 1):
        if i not in dict:
            print i
            sum += i
    print sum

insert_to_dictionary()
print_answer()

set

You build a dictionary to take advantage of the fast \$O(1)\$ membership test of the keys, but you never use the value (that is always 1), so you could just use a set that has the same \$O(1)\$ membership test but no values.

Returning the result

It is standard practice to return the results, not print them. If a result is returned, the user of the function may decide to do anything with it, including printing it. If you just print the result, no further re-use is possible.

Avoid globals when unnecessary

Globals may be changed anytime, from anywhere in your program. If you modify a global once wrongly by accident the whole program goes bogus. Just return the dict from insert_to_dictionary (I would call it abundant_sums because types should be in names and it is more descriptive.)

Use the built-ins

sum = 0
for i in range(1, 28123, 1):
    if i not in dict:
        print i
        sum += i
print sum

Becomes:

return sum(i for i in range(1, 28123, 1) if i not in set_)

I also avoided printing long lists of numbers because is not required (just the final answer is required).


Using JavaScript callback to conditionally send email I have an app where users at some point select the amount of tasks they have completed. If they have only completed 3 or less then 3 tasks then I send an email to the system admin to inform them.

But at the same time as the email is being sent the I want the data to be saved into the database. To achieve this I implemented a callback (or what I think is a callback.)

Is the below implementation okay?

if(req.body.sessionNo == 3){
                newDoc.sessionThreeMileStones = req.body.sessionThreeMileStones;
                // CALLBACK!!!
                checkMileStones(req.body,req.body.sessionThreeMileStones, sendMail)
    }

//SAVING THE DATA INTO MONGODB
newDoc.save(function(err, data) {
                if (err) {
                    sendJsonResponse(res, 400, err)
                }
                else {
                    incrementSessionTypesTotal(req, res);
                    sendJsonResponse(res, 200, data);
                }
            });

  // PASSING THE CALLBACK
  function checkMileStones(body,milestones,callback){
    if(milestones.length <= 3){
        //CALLING THE CALLBACK
        callback(body,milestones)
    } else {
        console.log("Not required");
    }
};

 // ACTUAL CALLBACK FUNCTION
 function sendMail(data,milestones){
    var data = {
                    from: 'App Team',
                    to: '',
                    subject: 'Milestones Alert - Session ' + data.sessionNo,
                    text: 'Hi ' + '\n\n' + data.fullName + ' from ' + data.company + ' has submitted the data for 3rd session with ' + data.clientName +'.\n' + 'They have only completed ' + milestones.length + ' milestones so far.'
                        };

                        mailgun.messages().send(data, function(error, body) {
                            console.log("sending email " + body)
                       });
}

Your implementation will work but in my opinion you have made your code complicated for no reason. You are violating the "Single Responsibility" principle here by making your "checkMilestones" method do two things

Check if milestone is reached
Send email

You could have simplified this as follows:

(req.body.sessionThreeMileStones.length <=3) ? sendMail() : doNothing();

This way your code is more readable and also easy to debug.


Using a Subject to trigger a music list to reload In my Android app I have a Service that is periodically polling a server for a music playlist XML. For certain occasions I also want to trigger a reload manually.

I am using Retrofit for the server communication and my Service exposes an Observable<Playlist> to which some other components of the app can subscribe. At the moment there are two such subscribers: One Fragment that contains the playback controls and one other Service that manages the actual audio streaming as well as the updates to the Notifications.

Now, I want all Subscribers to receive any new playlist info as soon as it becomes available. In particular this means that if I trigger a reload manually from the Fragment, the Service should also immediately receive the server response.

No matter how I turn it, all my solutions need a Subject. Here's the one I like best:

private Observable<MusicInfoResponse> mReloadingObservable;
private PublishSubject<Long> mManualRefreshesSubject = PublishSubject.<Long>create();

private void setupObservable() {

    Observable<Long> timer = Observable.timer(0, 15, TimeUnit.SECONDS);

    Observable<Long> pulses = Observable.merge(timer, mManualRefreshesSubject);

    mReloadingObservable = pulses
        .flatMap(new Func1<Long, Observable<MusicInfoResponse>>() {

            @Override
            public Observable<MusicInfoResponse> call(Long aLong) {
                Log.d(LOG_TAG, "reloading music info XML");
                return reloadMusicInfo();
            }
        })
        .share();
}

public Observable<MusicInfoResponse> subscribeToMusicInfo() {
    return mReloadingObservable;
}

public void triggerManualRefresh() {
    mManualRefreshesSubject.onNext(1l);
}

Since, it seems to me, one should generally avoid Subjects and try to use only normal Observables instead my question is: Is there any way to this that does not need Subjects? Is this a case where using Subjects is the way to go?

And also: What are the main drawbacks of Subjects in general?

There is no rule like

  one should generally avoid Subjects

You should just be careful around them, like you have. Just as a rule of thumb, keep Subjects private (inside your class), and if you want the outside world to be able to subscribe to it, just call subject.asObservable.

As for your code, you can perform the setupObservable() inside an obervable.onSubscribe() so that you have a cold observable and not a hot one.

If you really have to remove the Subject, you can do a Observable.create(subsriber -> ...). This subscriber variable would be the replacement for your mManualRefreshesSubject.

Frankly, there is not much difference between either pattern. The only thing you should do is check whether the subject.isUnsubscribed() / subscriber.isSubscribed. One benifit of using a subscriber is that you make sure to do stuff onSubscribe and not before.


Number to Roman numerals I've been working on numerals conversion lately. Now the JavaScript course I'm following asked me to do something similar for Roman numerals.
To keep things fresh and given the amount of test-cases provided I decided to write this one Test-Driven Development style. That is, for as much as I understand it.
First I check whether it's dividable by a full numeral (M, C, etc.). After that I have to reverse the string because the numerals were added in reverse order. The next step is to translate all combinations into their correct form using regex and a translation map. The functions were written in that order and fixing the problem the last part caused.
So far it looks very messy. Is this how one is supposed to solve problems TDD style? There is definitely a lot of code duplication going on, could this be fixed with another map?
Challenge

Convert the given number into a Roman numeral.
All Roman numerals answers should be provided in upper-case.

Test cases
convert(5) // "V".
convert(9) // "IX".
convert(12) // "XII".
convert(16) // "XVI".
convert(29) // "XXIX".
convert(44) // "XLIV".
convert(45) // "XLV"
convert(68) // "LXVIII"
convert(83) // "LXXXIII"
convert(97) // "XCVII"
convert(99) // "XCIX"
convert(500) // "D"
convert(501) // "DI"
convert(649) // "DCXLIX"
convert(798) // "DCCXCVIII"
convert(891) // "DCCCXCI"
convert(1000) // "M"
convert(1004) // "MIV"
convert(1006) // "MVI"
convert(1023) // "MXXIII"
convert(2014) // "MMXIV"
convert(3999) // "MMMCMXCIX"

Code
function convert(num) {
  roman = "";
  for (var i = 0; i < num; i++) {
    //MDCLXVI
    if (!(num % 1000)) { roman += "M"; num -= 1000; }
    else if (!(num % 500)) { roman += "D"; num -= 500; }
    else if (!(num % 100)) { roman += "C"; num -= 100; }
    else if (!(num % 50)) { roman += "L"; num -= 50; }
    else if (!(num % 10)) { roman += "X"; num -= 10; }
    else if (!(num % 5)) { roman += "V"; num -= 5; }
    else if (!(num % 1)){ roman += "I"; num -= 1; }
  }
  roman = roman.split('').reverse().join('');
  var translationMap = {
    DCCCC : 'CM',
    CCCC : 'CD',
    LXXXX : 'XC',
    XXXX : 'XL',
    VIIII : 'IX',
    IIII : 'IV',
  };
  for (var i in translationMap) {
    roman = roman.replace(new RegExp(i,'g'), translationMap[i]);
  }
  return roman;
}

convert(3999);

Run it at repl.it

Roman letter to value map

if (!(num % 1000)) { roman += "M"; num -= 1000; }
else if (!(num % 500)) { roman += "D"; num -= 500; }
else if (!(num % 100)) { roman += "C"; num -= 100; }
else if (!(num % 50)) { roman += "L"; num -= 50; }
else if (!(num % 10)) { roman += "X"; num -= 10; }
else if (!(num % 5)) { roman += "V"; num -= 5; }
else if (!(num % 1)){ roman += "I"; num -= 1; }

You should be using a map here to store the roman numeral values and their corresponding characters:

var romanCharacterMap = {
    "M": 1000,
    "D": 500,
    ...
}

With this, you can easily add on more letters if you ever felt like expanding it. Now, here is what your code would look like there:

while (num > 0) {
    for(var romanCharacter in romanCharacterMap) {
        var value = romanCharacterMap[romanCharacter];
        if(!(num % value)) {
            roman += romanCharacter;
            num -= value;
            break;
        }
    }
}

Then, to OOP this code up, you could move this function and the new map to an object to keep things together:

var RomanNumberalConverter = {
    ...
}

Then, the map won't be created every time the function is called; it will be created and referenced once.

Moar regexes... moar!

In this loop:

  for (var i in translationMap) {
    roman = roman.replace(new RegExp(i,'g'), translationMap[i]);
  }

Every iteration, you are creating a regex for every entry in the map. However, every time this function is called, the same regexes are created because that map is the same every time.

To speed things up, try creating the regex once and keeping it in the map that is also in this RomanNumberConverter object:

translationMap: {
    DCCCC: {
        replace: "CM",
        regex: /DCCCC/g
    },
    ...
}

Your code will now be faster because a new series of regexes doesn't have to be created every function call.


PreWarmCache for MVC Application with Stopwatch Infinite Loop I used the information from the article "Auto-Start ASP.NET Applications (VS 2010 and .NET 4.0 Series)" to create a background task that runs on an infinite loop. Ultimately, this program is going to be consuming a REST API to get data from a remote web site and insert records into my database. For the time being, I am just doing a basic insert.

public class PreWarmCache : System.Web.Hosting.IProcessHostPreloadClient
{
    private static BackgroundTaskContext db = new BackgroundTaskContext();
    private static Timer _timer;

    public void Preload(string[] parameters)
    {
        // Perform initialization and cache loading logic here...
        try
        {
            var doStuff = new DoStuff();
            doStuff.DoStuffName = "Test from PRELOAD INIT " + DateTime.Now;
            db.DoStuffs.Add(doStuff);
            db.SaveChanges();
        }
        catch
        {
        }

        var timeInMilliseconds = 0;
        _timer = new Timer(Callback, null, timeInMilliseconds, Timeout.Infinite);

    }

    public static void Callback(Object state)
    {
        var timeInMilliseconds = 5000;
        Stopwatch watch = new Stopwatch();

        watch.Start();

        // Update the database
        try
        {
            var doStuff = new DoStuff();
            doStuff.DoStuffName = "Test from CALLBACK " + DateTime.Now;
            db.DoStuffs.Add(doStuff);
            db.SaveChanges();
        }
        catch
        {
        }

        _timer.Change(Math.Max(0, timeInMilliseconds - watch.ElapsedMilliseconds), Timeout.Infinite);
    }
}

There are some things that you could have done better certainly.

My first pick is the class name DoStuff. Please try pick a more meaningful name like Action or Task.

In this class you seem to be appending the current time to the property DoStuffName (which should also be renamed accordingly). You could pass the name in the constructor and append the current time instead, like:

public class Task{
   public Task(string name){
      Name = name + " " + DateTime.Now;
   }
   public string Name{
     get; private set;
   }
}

You also seem to have one of the most evil bad practises of programming - the empty catch block. Be sure to, at least, log the exception somewhere.


Refactor multiple condition statements in map function I would love some help or some directions with refactoring this block of code. It perfectly works but it kind of looks ugly ;). It was messier but I tried to make it DRY-er.

  const uploadedFiles = images.map((item, index) => {
  if (images.length < 2) {
    if (item.file.name.match(/.(gif)$/i)) {
      return (
        <ImageGif
          key= {index}
          src= {item.blobUrl}
          onClose={this.props.removeImage}
        />
      );
    }

    return (<ImageContainer
      src={item.blobUrl}
      key={index}
      id={index}
      onClose={this.props.removeImage}
    />);
  }

  if (images.length >= 2) {
    if (MAX_SIZE === index + 1) {
      return (<ImageContainer
          src={item.blobUrl}
          key={index}
          id={index}
          onClose={this.props.removeImage}
          hiddenImages={hiddenImages}
        />);
    }
    if (MAX_SIZE !== index + 1) {
      return (<ImageContainer
          src={item.blobUrl}
          key={index}
          id={index}
          onClose={this.props.removeImage}
        />);
    }
  }

  return null;
});

Thank you and have a nice day!

Use ES2017 object spread:

const uploadedFiles = images.map((item, index) => {
  const props = {
    key: index,
    src: item.blobUrl,
    onClose: this.props.removeImage,
  };

  const isSingleGif = images.length === 1 && /\.gif$/i.test(item.file.name);
  if (isSingleGif) {
    return (<ImageGif {...props} />);
  }

  const isLastOfVisible = index === MAX_SIZE - 1 && index > 0;
  return (<ImageContainer
    id={index}
    {...props}
    {...isLastOfVisible && {hiddenImages}}
  />);
});

Not tested.

Notes:

images.length < 2 was misleading and confusing. The .map callback runs only when there are some elements so 0 is not possible. Simply compare with 1.
images.length >= 2 is superfluous and thus confusing: the previous check ensured this is always the case.
MAX_SIZE === index + 1 this yoda style obfuscates the actual goal, which is to determine whether the element is the last in the range.
MAX_SIZE !== index + 1 is superfluous and thus confusing: the previous check ensured this is always the case.
/.(gif)$/i incorrectly allowed any character before gif. The dot should be escaped. Also, no need for the slower .match if you don't use the captured strings. Use .test


Python solution to Code Jam's 'Rounding Error' The "Rounding Error" problem of Round 1B of Google Code Jam 2018 is as follows:

  Problem

  To finally settle the age-old question of which programming language is the best, you are asking a total of N people to tell you their favorite language. This is an open-ended question: each person is free to name any language, and there are infinitely many languages in the world.

  Some people have already responded, and you have gathered this information as a list of counts. For example, 1 2 means that you have asked 3 people so far, and one picked a particular language, and the other two picked some other language.

  You plan to publish the results in a table listing each language and the percentage of people who picked it. You will round each percentage to the nearest integer, rounding up any percentage with a decimal part equal to or greater than 0.5. So, for example, 12.5% would round up to 13%, 99.5% would round up to 100%, and 12.4999% would round down to 12%.

  In surveys like this, sometimes the rounded percentages do not add up to exactly 100. After you are done surveying the remaining people, what is the largest value that the rounded percentages could possibly add up to?

  Input

  The first line of the input gives the number of test cases, T. T test cases follow; each consists of two lines. The first line consists of two integers N and L: the total number of people in the survey, and the total number of different languages represented among the people who have already responded. The second line consists of L integers Ci; the ith of these is the number of people who said that the ith of the represented languages was their favorite.

  Output

  For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the largest value that the percentages could possibly add up to, as described above.

  Limits

  1 ≤ T ≤ 100.
  1 ≤ L < N.
  1 ≤ Ci, for all i.
  The sum of all Ci values < N.
  Time limit: 10 seconds per test set.
  Memory limit: 1GB.

This is my Python solution.  However, I get the 'Time Limit Exceeded' result even for the smallest test case. How can I speed up this solution?

from functools import reduce

def main():
    def gen_sums(total, freq, remaining):
        """Generate percentages' sums"""
        if not remaining:
            yield reduce(lambda x, y: x + (y*100+total//2)//total, freq, 0)
        else:
            seen = set()

            for i in range(len(freq)):
                if not freq[i] in seen:
                    yield from gen_sums(total,
                                        freq[:i] + [freq[i]+1] + freq[i+1:],
                                        remaining-1)
                    seen.add(freq[i])

            yield from gen_sums(total, freq+[1], remaining-1)

    T = int(input())

    for i in range(1, T+1):
        total_people, num_languages = map(int, input().split())
        languages_frequency = [int(x) for x in input().split()]

        if not 100 % total_people:
            print('Case #{}: {}'.format(i, 100))
            continue

        not_responded = total_people - sum(languages_frequency)

        max_percentage = max(gen_sums(total_people, languages_frequency,
                                      not_responded))

        print('Case #{}: {}'.format(i, max_percentage))

main()

1. Review

It is hard to test this code because it gets its data from standard input.

This means that in order to test it or measure its performance you have to write the test case to a file and then run the code with standard input redirected from that file. It would be easier to test if the code were refactored so that the input-reading part of the code was in a separate function from the problem-solving part, like this:

from functools import reduce

def gen_sums(total, freq, remaining):
    """Generate percentages' sums"""
    if not remaining:
        yield reduce(lambda x, y: x + (y*100+total//2)//total, freq, 0)
    else:
        seen = set()
        for i in range(len(freq)):
            if not freq[i] in seen:
                yield from gen_sums(total,
                                    freq[:i] + [freq[i]+1] + freq[i+1:],
                                    remaining-1)
                seen.add(freq[i])
        yield from gen_sums(total, freq+[1], remaining-1)

def max_percentage(total_people, languages_frequency):
    if not 100 % total_people:
        return 100
    not_responded = total_people - sum(languages_frequency)
    return max(gen_sums(total_people, languages_frequency, not_responded))

def main():
    T = int(input())
    for i in range(1, T+1):
        total_people, num_languages = map(int, input().split())
        languages_frequency = [int(x) for x in input().split()]
        result = max_percentage(total_people, languages_frequency)
        print('Case #{}: {}'.format(i, result))

Now it's easy to test the code from the interactive interpreter or from a unit test, for example:

>>> max_percentage(11, [1, 2, 3, 4])
99

and easy to measure its performance:

>>> from timeit import timeit
>>> timeit(lambda:max_percentage(14, []), number=1)
8.237278351996792

2. Performance

As demonstrated above, the code in the post takes more than 8 seconds to figure out that when there are 14 voters (and no votes cast yet), the maximum rounded percentage is 101%.

Why does the code in the post take so long to solve this problem? Well, it's because it carries out a search over all possible assignments of votes. But if there are \$n\$ voters then there are of the order of $$\exp{\pi\sqrt {2n \over 3}}$$ possible assignments of votes (see the asymptotic formula for the partition numbers) and so the runtime is exponential in the number of votes.

But in fact the problem is easy to solve by hand with a little bit of mathematics. If there are 14 voters, then each vote is worth \${100 \over 14} = 7{1\over7}\$ percent, and so four votes are worth \$28{4\over7}\$ percent, which rounds up to 29. Fewer than four votes will round down, and more than four will be wasteful since the extra votes over four could be used to contribute to another block of four votes. So the maximum rounded percentage is found when we group as many of the votes as possible into blocks of four votes. In this case there are three such blocks, leaving two votes over, giving a rounded total of \$29·3 + 14 = 101\$.

Similar analysis shows that if there are 19 voters, then each voter contributes \${100\over19} = 5{5\over19}\$ percent, and so it is most efficient to put voters in pairs, because two votes contibute \$10{10\over19}\$ percent, which rounds up to 11. So we have nine pairs of votes and one left over, giving a rounded total of \$11·9 + 5 = 104\$. But it will be a very long time before max_percentage(19, []) returns the result.

So searching over all possible assignments of votes is not going to work even for moderately large problem sizes. Instead, you need to program the kind of mathematical analysis that I carried out in the examples above. I'm not going to spoil the problem for you by giving away my solution, but I'll just show one performance measurement:

>>> timeit(lambda:max_percentage2(14, []), number=1)
0.00011452200124040246

This is more than 70,000 times faster than the code in the post.


Google Foobar Level 1 - Minion Task Schedule I recently just stumbled upon a post regarding Google Foobar Level 2 and decided to try it out myself but starting from Level 1. The description and code are shown below.

Write a function called answer(data, n) that takes in a list of less
than 100 integers and a number n, and returns that same list but with all of the numbers that occur more than n times removed entirely. The returned list should retain the same ordering as the original list - you don't want to mix up those carefully planned shift rotations! For instance, if data was [5, 10, 15, 10, 7]
and n was 1, answer(data, n) would return the list [5, 15, 7] because 10 occurs
twice, and was thus removed from the list entirely.
Constrains:
Standard libraries are supported except for bz2, crypt, fcntl, mmap,
pwd, pyexpat, select, signal, termios, thread, time, unicodedata, zipimport, zlib.
Test Cases:
Inputs:
(int list) data = [1, 2, 3]
(int) n = 0
Output:
(int list) []
Inputs:
(int list) data = [1, 2, 2, 3, 3, 3, 4, 5, 5]
(int) n = 1
Output:
(int list) [1, 4]
Inputs:
(int list) data = [1, 2, 3]
(int) n = 6
Output:
(int list) [1, 2, 3]

Code:
def answer(data, n):
    if len(data) > 99:
        exit('List contains more than 100 elements')
    print('data:\n', data) #for error-checking

    count = dict()
    for i in data:
        count.setdefault(i, 0)
        count[i] += 1
    print('count:\n', count) #for error-checking

    for k, v in count.items():
        if v > n:
            for i in range(v):
                data.remove(k)

    return data

I decided to also test the code myself by using test cases and a new list containing random numbers
data1 = [1, 2, 3]
n1 = 0

data2 = [1, 2, 2, 3, 3, 3, 4, 5, 5]
n2 = 1

data3 = [1, 2, 3]
n3 = 6

data4 = [random.randint(1, 15) for i in range(0, 99)]
n4 = 6

ans1 = answer(data1, n1)
print('ans1:\n', ans1, '\n')

ans2 = answer(data2, n2)
print('ans2:\n', ans2, '\n')

ans3 = answer(data3, n3)
print('ans3:\n', ans3, '\n')

ans4 = answer(data4, n4)
print('ans4:\n', ans4, '\n')

Output:
data:
 [1, 2, 3]
count:
 {1: 1, 2: 1, 3: 1}
ans1:
 []

data:
 [1, 2, 2, 3, 3, 3, 4, 5, 5]
count:
 {1: 1, 2: 2, 3: 3, 4: 1, 5: 2}
ans2:
 [1, 4]

data:
 [1, 2, 3]
count:
 {1: 1, 2: 1, 3: 1}
ans3:
 [1, 2, 3]

data:
 [15, 9, 14, 10, 13, 8, 7, 2, 10, 3, 10, 11, 9, 9, 10, 7, 5, 11, 12, 14, 1, 5, 14, 15, 11, 2, 13, 2, 6, 1, 6, 8, 3, 15, 8, 6, 6, 13, 14, 14, 2, 14, 12, 6, 15, 4, 7, 5, 13, 8, 8, 4, 7, 15, 6, 1, 2, 11, 14, 6, 8, 4, 10, 4, 2, 9, 6, 14, 11, 12, 8, 15, 7, 15, 6, 1, 14, 8, 5, 14, 6, 10, 8, 1, 4, 15, 11, 9, 11, 10, 13, 13, 9, 7, 7, 4, 4, 12, 12]
count:
 {15: 8, 9: 6, 14: 10, 10: 7, 13: 6, 8: 9, 7: 7, 2: 6, 3: 2, 11: 7, 5: 4, 12: 5, 1: 5, 6: 10, 4: 7}
ans4:
 [9, 13, 2, 3, 9, 9, 5, 12, 1, 5, 2, 13, 2, 1, 3, 13, 2, 12, 5, 13, 1, 2, 2, 9, 12, 1, 5, 1, 9, 13, 13, 9, 12, 12]

Any input is appreciated. Thank you :-)

if len(data) > 99:
    exit('List contains more than 100 elements')

I'd change that error message to something like 'List contains a hundred or more elements'. I might also raise a ValueError instead of calling exit. I think that's more appropriate for an error that the user may want to catch.

You can get rid of your call to setdefault by using a defaultdict instead:
from collections import defaultdict

. . .

count = defaultdict(int)  # int is a function that returns 0 when no args are given to it
for i in data:
    count[i] += 1

The gain here isn't huge, but they're handy in many cases.
collections.Counter would probably be appropriate here as well, but I've only used it once, so I can't show a good example of it.


Mapping a user input string to a corresponding block of code My idea is I can define a block of code (inline) that corresponds to an input string then can call that block of code when given that input.

I'm used to this sort of structure in JavaScript like so:

var lookup = {
  "foo": function() { ... },
  "bar": function() { ... },
};

lookup["foo"];

And I'm looking for a C# equivalent. So far I've come up with the following and it seems to work, but I don't know if it could be simplified or improved upon.

class CortanaFunctions
{
        /*
        This is the lookup of VCD CommandNames as defined in
        CustomVoiceCommandDefinitios.xml to their corresponding actions
        */
        public readonly static Dictionary<string, Delegate> vcdLookup = new Dictionary<string, Delegate>{

            /*
            {<command name from VCD>, (Action)(async () => {
                 <code that runs when that commmand is called>
            })}
            */

            {"OpenToDoList", (Action)(async () => {
                StorageFile file = await Package.Current.InstalledLocation.GetFileAsync(@"ToDo.doc");
                await Launcher.LaunchFileAsync(file);
            })},

            {"OpenReddit", (Action)(async () => {
                 Uri website = new Uri(@"http://www.reddit.com");
                 await Launcher.LaunchUriAsync(website);
             })},

        };

        /*
        Register Custom Cortana Commands from VCD file
        */
        public static async void RegisterVCD()
        {
            StorageFile vcd = await Package.Current.InstalledLocation.GetFileAsync(
                   @"CustomVoiceCommandDefinitions.xml");
            await VoiceCommandDefinitionManager
                   .InstallCommandDefinitionsFromStorageFileAsync(vcd);
        }

        /*
        Look up the spoken command and execute its corresponding action
        */
        public static void RunCommand(VoiceCommandActivatedEventArgs cmd)
        {
            SpeechRecognitionResult result = cmd.Result;
            string commandName = result.RulePath[0];
            vcdLookup[commandName].DynamicInvoke();
        }

 }

VCD file:

<?xml version="1.0" encoding="utf-8" ?>

<VoiceCommands xmlns="http://schemas.microsoft.com/voicecommands/1.2">
  <CommandSet xml:lang="en-us" Name="CustomCommands">
   <CommandPrefix> listen here </CommandPrefix>
    <Example> open to do list, open reddit</Example>

    <Command Name="OpenToDoList">
      <Example> open to do list </Example>
      <ListenFor> open to do list</ListenFor>
      <Feedback> opening your to do list</Feedback>
      <Navigate/>
    </Command>

    <Command Name="OpenReddit">
      <Example> open reddit </Example>
      <ListenFor> open reddit </ListenFor>
      <Feedback> opening reddit </Feedback>
      <Navigate/>
    </Command>
  </CommandSet>
</VoiceCommands>

A problem with the code is that the async lambdas in the dictionary are actually async void.

  Async void methods have different error-handling semantics. When an exception is thrown out of an async Task or async Task<T> method, that exception is captured and placed on the Task object. With async void methods, there is no Task object, so any exceptions thrown out of an async void method will be raised directly on the SynchronizationContext that was active when the async void method started. -- Async/Await - Best Practices in Asynchronous Programming

It's also confusing because vcdLookup[commandName].DynamicInvoke() looks like a blocking call, but it isn't. Consider this code:

private static readonly Dictionary<string, Delegate> vcdLookup = new Dictionary<string, Delegate>
{
    { "OpenToDoList", (Action)(async () =>
        {
            Console.WriteLine("Opening to-do list...");
            await Task.Delay(TimeSpan.FromSeconds(1));
            Console.WriteLine("Opened to-do list");
        })
    }
};

public static void RunCommand(string command)
{
    vcdLookup[command].DynamicInvoke();
    Console.WriteLine("Finished command");
}

If we call RunCommand("OpenToDoList"), the output is

  Opening to-do list...

  Finished command

  Opened to-do list

I would recommend instead to change vcdLookup to a Dictionary<string, Func<Task>>.

private static readonly IReadOnlyDictionary<string, Func<Task>> vcdLookup = new Dictionary<string, Func<Task>>
{
    { "OpenToDoList", async () =>
        {
            StorageFile file = await Package.Current.InstalledLocation.GetFileAsync(@"ToDo.doc");
            await Launcher.LaunchFileAsync(file);
        }
    }
};

public static async Task RunCommandAsync(string command)
{
    SpeechRecognitionResult result = command.Result;
    string commandName = result.RulePath[0];
    await vcdLookup[commandName]();
}

A couple of other notes:

Async methods should have the suffix Async, by convention
You probably don't want to make vcdLookup public, exposing it to the world
You can declare vcdLookup as an IReadOnlyDictionary so that its contents are not modified after creation


OO coding style in short Ruby scripts I've been using Ruby for about a year now, mostly for small scripts with uses ranging from data munging to DevOps tasks. However, I am not intimately familiar with OOP (I appreciate the functional programming approach I'm often able to take with Ruby) and so I think my code is harder to read and debug than it could be.

I do not think my code is idiomatically Ruby, and I think I'm using a procedural style. I've included a recently-written Ruby script as an example, but at what point should one refactor into a OOP style? Is it always helpful to begin with a OOP structure? And I mean helpful in two senses: the sense that it will be easier for other team members to read the code; and also in the sense that it will make the program more robust and easier to debug.

The script below was intended as a small auditing tool. It takes a CSV (in two possible formats) and compares it to a database, but it has to do a lot of munging and matching because the results are not easily directly comparable.

#!/usr/bin/env ruby

require 'csv'
require 'date'
require 'json'
require 'mysql2'
require 'pp'

# Command line argument handling
if ARGV.length < 2
  puts "Usage: <CSV path or filename> <User's screenname>"
  puts "Outputs JSON of results we do not have in our database"
  exit
end

ARGV.each do |arg|
  # If the arg is a file that exists...
  File.file?(arg) ? @file = arg : @user = arg
end

def redacted?(filename)
  /redacted/.match(filename)
end

def make_redacted(csv)
  header = csv.slice!(0).map {|x| x.split.join.downcase.gsub(/\(\$\)/, '').to_sym}
  fd_csv = csv.map {|row| Hash[header.zip(row)]}
  fd_csv.map do |row|
    row[:name] = row[:title]
    row[:hashtag] = row[:sport]
    row[:opponent_score] = row[:oppscore]
    row[:place_finished] = row[:position].to_i
    row[:prize] = row[:winnings].to_f
    row[:date] = Date.parse(row[:date]).strftime('%Y-%m-%d')
    #row[:opponent_name] = row[:opponent]
    row[:score] = row[:score].to_f
    row[:entrants] = row[:entries].to_i
    row[:buy_in] = row[:entry].to_f
    row.delete_if { |k,v| [:title, :entries, :sport, :oppscore, :position,
     :opponent].include? k }
   end
 end

 def make_other_redacted(csv)
  ## Same sort of deal, except mapping other fields
  return dd_csv
end

# Read the database into memory too
def our_results
  # Set site ID to magic int
  site_id = redacted?(@file) ? 2 : 20
  db_hash = []
  client = Mysql2::Client.new(:host     => "hostname",
    :username => "etc",
    :password => "etc",
    :port     => etc,
    :database => "etc"
    )
  sql = "long sql query with some #{string_interpolation}"

  # Had to turn off casting due to some issues in the DB results
  db_results = client.query(sql, :symbolize_keys => true, :cast => false).each do |row|
    # Here I'm mapping hash names again
    row[:score] = row[:score].to_f
    # etc...
    db_hash << row
  end
  db_hash
end

# Takes a single object and an array
def match_redacted?(source, target)
  target.detect{|x| source[:prize] == x[:prize] &&
    # Match based on a list of hash values matching
  }
end

def match_other_redacted?(source, target)
  target.detect{|x| source[:prize] == x[:prize] &&
    # Same thing, different matching criteria
  }
end

def get_remainder(source, target)
  if redacted?(@file)
    source.delete_if {|s| match_redacted?(s, target)}
  else
    source.delete_if {|s| match_other?(s, target)}
  end
end

db_results = our_results()
# Read the csv into memory, fix it up
csv = CSV.read(@file)
source = fanduel?(@file) ? make_redacted(csv) : make_other_redacted(csv)
# Delete the results from the source that we match in the DB
remainder = get_remainder(source, db_results)
unless remainder.empty?
  puts JSON.generate(remainder)
end

Never use OOP just because people say it's cool. If you do not know how to apply it, that means you just do not need it in this task. That's it. Forget about OOP. Involving it without much need only makes code worse and unreadable.


Should a year and month be stored as separate fields or as a date? We have a table with calculated data that groups sales by product, year and month, to provide fast querying for statistics.

My colleague argues that the year and month should be two separate fields, because a day is meaningless.

I want it as a date field, because using two separate fields leads to awkward code like this

var lastTwelveMonths = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-11);
var result = data.Where(item =>
    (item.Year > lastTwelveMonths.Year
    || (item.Year == lastTwelveMonths.Year && item.Month >= lastTwelveMonths.Month));

instead of this

var lastTwelveMonths = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-11);
var result = data.Where(item => item.YearAndMonthAsDate >= lastTwelveMonths);

I understand his argument, but the code is harder to read and there's a higher chance on bugs when doing date/time calculations without using date/time objects. I also can't cast it to a DateTime in the query because I'm using LINQ to Entities.

Which method is the better one?

In general it really depends on the use cases of your data.  If you need to perform queries using just year or just month then you reduce complexity in the code and queries by having separate fields.

However, if you aren't bounding by just a year or just a month then you would want to use a date field.

Professionally I use date or string fields (YYYYMMDD) when representing dates and times because the speedup you get from single year/month fields is small with todays databases (assuming things are correctly indexed).


Grouping work hours for consecutive days Problem Description
The problem was initially posted here: Parse and clean up text block of store hours in Python.
Given the following multi-line string:
"""Hours
Monday 9:30 AM - 9:00 PM
Tuesday 9:30 AM - 9:00 PM
Wednesday 9:30 AM - 9:00 PM
Thursday 9:30 AM - 9:00 PM
Friday 9:30 AM - 11:00 PM
Saturday 9:30 AM - 11:00 PM
Sunday 11:00 AM - 6:00 PM
Holiday Hours
Thanksgiving Day 11:00 AM - 6:00 PM"""

Group the consecutive weekdays by the work hours, producing the following output:
"""Mon-Thu 9:30AM-9:00PM
Fri-Sat 9:30AM-11:00PM
Sun & Hol 11:00AM-6:00PM"""

Solution
My approach is based on parsing the weekday lines, splitting by the first space and then using itertools.groupby() to sort by the second item of every row, using the groupby's implementation detail - it would only group the consecutive matches together:
from itertools import groupby
from operator import itemgetter

data = """Hours
Monday 9:30 AM - 9:00 PM
Tuesday 9:30 AM - 9:00 PM
Wednesday 9:30 AM - 9:00 PM
Thursday 9:30 AM - 9:00 PM
Friday 9:30 AM - 11:00 PM
Saturday 9:30 AM - 11:00 PM
Sunday 11:00 AM - 6:00 PM
Holiday Hours
Thanksgiving Day 11:00 AM - 6:00 PM"""

# filter relevant rows with weekdays only
rows = [row.split(" ", 1) for row in data.splitlines()[1:-2]]

# group consecutive days by a time range
result = []
for time_range, group in groupby(rows, key=itemgetter(1)):
    days_in_group = [item[0] for item in group]

    first_day, last_day = days_in_group[0][:3], days_in_group[-1][:3]
    range_end = "-" + str(last_day) if first_day != last_day else ""

    result.append("{begin}{end} {time_range}".format(begin=first_day,
                                                     end=range_end,
                                                     time_range=time_range))

print("\n".join(result))

Is this the most optimal solution to the problem? Is it Pythonic? What would you improve code quality-wise?

magic numbers

In

rows = [row.split(" ", 1) for row in data.splitlines()[1:-2]]

the 1 & -2 magic numbers are a bit of a wart. Perhaps you'd like to create a generator that knows to suppress 'Hours' and that won't yield any further lines after 'Holiday Hours'.

Also,

first_day, last_day = days_in_group[0][:3], days_in_group[-1][:3]

has some magic numbers, but arguably they make more sense. You could make your generator responsible for day parsing, with yield day[:3], time_range.

variable renaming

In your string formatting, you choose to rename first_day to begin, and range_end to end. I suppose my advice is "don't do that". Or if there's a name you prefer for those variables, use that consistently throughout.

In

days_in_group = [item[0] for item in group]

the identifier item is a bit vague. pair would be better (or perhaps day_range if you lean toward the verbose).

global scope

You polluted the top-level namespace with rows and other identifiers. Your file cannot be reused via import. Please use the

if __name__ == '__main__':

idiom to bury these lines of code under def main(): or similar.

Overall, yes, this is sensible code, put together in pythonic fashion.


Command line tool for Italian language studies I made a small command line tool to help my Italian studies. Any thoughts on how it could be improved? I can't think of much but would like to be proved wrong.

import random

class RegularVerb(object):
    def __init__(self, name):
        self._name = name

    def name(self):
        return self._name

    def _make(self, verb_end):
        return self.name()[:-3] + verb_end

    def _build_condizionale_semplice(self, verb_forms, prefix):
        def verb_base(prefix):
            return (prefix + condizionale_semplice_base
                    for condizionale_semplice_base in
                    ['rei', 'resti', 'rebbe', 'remmo', 'reste', 'rebbero']
                   )
        return dict(zip(verb_forms, verb_base(prefix)))

class EreVerb(RegularVerb):
    def __init__(self, name, verb_forms):
        super(EreVerb, self).__init__(name)
        self._condizionale_semplice = self._build_condizionale_semplice(verb_forms, 'e')

    def condizionale_semplice(self, verb_form):
        return self._make(self._condizionale_semplice[verb_form])

class IreVerb(RegularVerb):
    def __init__(self, name, verb_forms):
        super(IreVerb, self).__init__(name)
        self._condizionale_semplice = self._build_condizionale_semplice(verb_forms, 'i')

    def condizionale_semplice(self, verb_form):
        return self._make(self._condizionale_semplice[verb_form])

class AreVerb(RegularVerb):
    def __init__(self, name, verb_forms):
        super(AreVerb, self).__init__(name)
        self._condizionale_semplice = self._build_condizionale_semplice(verb_forms, 'e')

    def condizionale_semplice(self, verb_form):
        return self._make(self._condizionale_semplice[verb_form])

class Questioner():

    def __init__(self, verb_forms, verbs):
        self._verb_forms = verb_forms
        self._verbs = verbs

    def _handle_answer(self, user_answer, correct_answer):
        if user_answer == correct_answer:
            print "bravo!"
        else:
            print "no, correct form is:", correct_answer

    def ask_random_condizionale_semplice(self):
        def ask(verb_form, verb):
            print "condizionale semplice for {0} in {1}?".format(verb.name(), verb_form),
            self._handle_answer(raw_input(), verb.condizionale_semplice(verb_form))
        ask(random.choice(self._verb_forms), random.choice(self._verbs))

def build_regular_verbs(verbs, verb_forms):
    def make(verb):
        if verb[-3:] == 'are':
            return AreVerb(verb, verb_forms)
        elif verb[-3:] == 'ire':
            return IreVerb(verb, verb_forms)
        elif verb[-3:] == 'ere':
            return EreVerb(verb, verb_forms)
        else:
            raise Exception("not a regular verb")
    return [make(v) for v in verbs]

def build_questioner(verb_forms, regular_verbs):
    return Questioner(verb_forms,
                      build_regular_verbs(
                        regular_verbs,
                        verb_forms
                      )
                     )

if __name__ == "__main__":
    questioner = build_questioner(
                        ['I sg', 'II sg', 'III sg', 'I pl', 'II pl', 'III pl'],
                        ['passare', 'mettere', 'sentire'],
                       )
    while True:
        questioner.ask_random_condizionale_semplice()

Maybe this could provide of a more neat way of relating verbs with veb_forms:

verb_binder = dict(are=AreVerb, ire=IreVerb, ere=EreVerb)

def build_regular_verbs(verbs, verb_forms):
    def make(verb):
        try:
            return verb_binder[verb[-3:]](verb, verb_forms)
        except KeyError:
            raise Exception("not a regular verb")

    return [make(v) for v in verbs]

not sure if verb_binder dictionary should be a module global or local to the function or maybe it should be located elsewhere, but this is the idea.


Handling multiple optional parameters in Spring I have an endpoint in my RestAPI which can receive 3 optional parameters and then find information in the database with these parameters, also it is possible to combine the parameters. So, in my controller I take a Map<String, Object> which contains these parameters and then pass it to the service level, where I check which parameters were passed and then I call a specific DAO method, depends on which combination of parameters do I have. Params A and B are of type String, and C is a Map. So in the service level it looks like this:
public Set<ResultEntry> getByParameters(Map<String, Object> query) {
    Set<ResultEntry> result = new HashSet<>();
    if (query.containsKey("a") && query.containsKey("b") && query.containsKey("c")) {
        result.addAll(myDao.getByABC(
                (String) query.get("a"), (String) query.get("b"),
                (Map<String, String>) query.get("c")
        ));
    } else if (query.containsKey("a") && query.containsKey("b") && !query.containsKey("c")) {
        result.addAll(myDao.getByAB(
                (String) query.get("a"), (String) query.get("b")
        ));
    } else if (query.containsKey("a") && !query.containsKey("b") && query.containsKey("c")) {
        result.addAll(myDao.getByAC(
                (String) query.get("a"), (Map<String, String>) query.get("c")
        ));
    } else if (!query.containsKey("a") && query.containsKey("b") && query.containsKey("c")) {
        result.addAll(myDao.getByBC(
                (String) query.get("b"), (Map<String, String>) query.get("c")
        ));
    } else if (query.size() == 1 && query.containsKey("a")) {
        result.addAll(myDao.getByA((String) query.get("a")));
    } else if (query.size() == 1 && query.containsKey("b")) {
        result.addAll(myDao.getByB((String) query.get("b")));
    } else if (query.size() == 1 && query.containsKey("c")) {
        result.addAll(myDao.getByC((Map<String, String>) query.get("c")));
    }
    return result;
}

Everything works fine, but I feel like this is not the best way to deal with such situations, using if-statements for each possible combination, so how can I improve it?

Although it works, the major issue with this approach is its extreme complexity and concreteness. If a new parameter d enters the game, it will became hellish to maintain!
What can be done to improve the current implementation, without changing the approach?

there are many repetitions of .containsKey(arg) calls. They can be extracted to respective booleans like hasA, hasB -> the code will be more readable.

there are many redundant casts. (String) query.get("a") and the others can be extracted into respective local var a = (String) query.get("a") -> it will also become shorter and more readable.

I think that the result variable might be avoided, if myDao.get* methods already return Sets.

How the design can be improved?
For the solution below, I suppose that the interface of the myDao object cannot be changed. If it could, there might be ways to play with method overloads, attempting to apply a pattern.
The current API of myDao looks very concrete and clear. The names of the methods mention each expected parameter and the order and the number of the arguments is predictable for each case. So the solution that I suggest below is based on the calculation of the method to invoke by reflection.
The name of the method to invoke on myDao can be calculated as follows:
private String calculateDaoMethodToInvoke(boolean hasA, boolean hasB, boolean hasC) {
  var builder = new StringBuilder("getBy");
  if (hasA) {
    builder.append("A");
  }
  if (hasB) {
    builder.append("B");
  }
  if (hasC) {
    builder.append("C");
  }
  return builder.toString();
}

We can also calculate the arguments to invoke this method with:
private Object[] calculateDaoMethodArgs(String a, String b, Map<String, String> c) {
  return Stream.of(a, b, c)
               .filter(Objects::nonNull)
               .toArray();
}

Now, since we know the name of the target method and the parameters to use, the Java reflection features can be used to produce the results.
We can define a wrapper around the Class.getMethod call, in order to retrieve the reference to the method of myDao to be invoked:
private Method extractDaoMethod(String daoMethodName, Object[] params) {
  try {
    var paramTypes = Arrays.stream(params)
                           .map(Object::getClass)
                           .toArray(Class[]::new);
    return Dao.class.getMethod(daoMethodName, paramTypes);
  } catch (NoSuchMethodException ex) {
    throw new IllegalStateException(ex);
  }
}

And its invocation can also be wrapped:
private Collection<ResultEntry> getByParams(String daoMethodName, Object[] params) {
  var method = extractDaoMethod(daoMethodName, params);
  try {
    return (Collection<ResultEntry>) method.invoke(myDao, params);
  } catch (IllegalAccessException | InvocationTargetException ex) {
    throw new IllegalStateException(ex);
  }
}

Finally, the getByParameters method is reduced to the following:
public Set<ResultEntry> getByParameters(Map<String, Object> query) {
  var a = (String) query.get("a");
  var b = (String) query.get("b");
  var c = (Map<String, String>) query.get("c");

  var daoMethodName = calculateDaoMethodToInvoke(a != null, b != null, c != null);
  var daoArgs = calculateDaoMethodArgs(a, b, c);
  return new HashSet<>(getByParams(daoMethodName, daoArgs));
}

Please note that there are no more rigid if - else if chaining, the algo became flat.
This approach allows to easily introduce new parameters, provided that the myDao API continues to respect the same convention for its method names.
There can be further improvements. For example, the signatures of calculateDaoMethodToInvoke and calculateDaoMethodArgs can be changed in order to accept varargs (and corresponding changes in the implementation). It will make the introduction of new parameters even easier.


Function to generate nearly sorted numbers I wrote function to generate nearly sorted numbers:

def nearly_sorted_numbers(n):
    if n >= 100:
        x = (int)(n/10)
    elif n >= 10:
        x = 9
    else:
        x = 4
    numbers = []
    for i in range(1,n):
        if i%x==0:
            numbers.append(random.randint(0,n))
        else:
            numbers.append(i)
return numbers

Have you any idea how improve my code?

def nearly_sorted_numbers(n):
    if n >= 100:
        x = (int)(n/10)

Use int(n//10), the // explicitly request integer division and python doesn't have casts

    elif n >= 10:
        x = 9
    else:
        x = 4

I wouldn't name the variable x, as it gives no hint as to what it means. I'd also wonder whether it wouldn't be better as a parameter to this function. It seems out of place to be deciding that here.

    numbers = []
    for i in range(1,n):
        if i%x==0:
            numbers.append(random.randint(0,n))
        else:
            numbers.append(i)
return numbers


How could I have approached this responsive image gallery differently? This gallery uses the Orbit gallery from the Foundation framework (version 3). I've set it up so that on smaller screens it appears as an accordion.

It works just fine, but is there a more concise way this could've been written? Perhaps in an object oriented way?

The script:

function activateSlider() {
    if (window.Foundation && window.matchMedia) {

      // Establishing media check
      widthCheck = window.matchMedia("(max-width: 767px)");
      if (widthCheck.matches) {
        $('.orbit-container').after($('.orbit-timer'));
        $('#slider, #slider li').attr('style', '');
        $('#slider').removeClass('orbit-slides-container').removeAttr('data-orbit').addClass('accordion-container');
        $('#slider li').removeAttr('data-orbit-slide').removeClass('active');
        $('.orbit-container > a, #slider li .slider-content').hide();
        $('#slider li:not(.active) .slider-content').css('display', 'none');

      //Init accordion click functions
        $('#slider li').unbind().bind('click', function(){
            $(this).toggleClass('active').siblings().removeAttr('class');
            $(this).siblings().find('.slider-content').slideUp();
          $(this).find('.slider-content').slideToggle();
        });
  }
  else
  {
    //If accordion styles are present, clean it up
    var OrbitStyles = ($('.accordion-container').length === 0);
    if (!OrbitStyles) {
        $('.orbit-container > a').show();
        $('#slider').removeClass('accordion-container');
        $('#slider').addClass('orbit-slides-container');
        $('#slider').attr('data-orbit', '');
        $('.orbit-bullets-container').before($('.orbit-timer'));
        $('.orbit-timer').removeClass('paused');
    }
   //Then set it up for the slider
      $('.slider-content').show();
      $('#slider li:first-child').addClass('active').siblings().removeAttr('class');
  }
 }
}

//Run the script
$(function(){
    activateSlider();
});

//Run the script on resize
if (window.addEventListener) {
   window.addEventListener('resize', debounce(function () {
    activateSearch();
    //fade in the slider while loading to prevent that second of ugly formatting
    if ($('#slider').length > 0) {
        $('#slider').delay(700).animate({ opacity: 1 }, 500);
    }
  }, 250));
} else {
    window.attachEvent('resize', debounce(function () {
      activateSearch();
      //fade in the slider while loading to prevent that second of ugly formatting
      if ($('#slider').length > 0) {
         $('#slider').delay(700).animate({ opacity: 1 }, 500);
      }
    }, 250));
}

And the html markup:

        Oh got walrus

More hence euphemistic oriole let tediously dear repeatedly.

          Read More

        Overslept wiped yikes

Much supreme quick rakishly tamarin

           Read More

The most important bit here is the resize handler, since it fires many times per scroll.

//Run on document ready
$(function () {

    // Cache the slider jQuery object
    var slider = $('#slider');

    // Pass in the existing reference. Explanation after the code
    activateSlider(slider);

    // Move out the debouncing function outside the resize handler
    // so that the function isn't recreated on every risize call
    function debounceAction() {
        activateSearch();

        //Personal preference. The "early return" looks better since
        // it avoids any additional indention
        if (!slider.length) return;

        slider.delay(700).animate({opacity: 1}, 500);

    }

    // Since you use jQuery, use it to abstract the resize function instead.
    $(window).on('resize', function () {
        // And all the handler's got to do is call debounce
        debounce(debounceAction, 250);
    });
});

As for your activateSlider, you should cache the fetched DOM elements into variables and reuse them when necessary. Each time you do something like $('.slider'), it looks for elements with class slider. Caching them avoids this searching. I have already done it with $('#slider') by fetching it once, and passing it into activateSlider.


Implementing data sync from multiple source using OOP concepts I am writing code to implement data sync from multiple sources. I want code to be maintainable to add more data sources if required.

Here is the pattern I wish to follow:

class Source1Client:

    def get_domain(self):

        pass

    def get_endpoint(self):

        pass

    def get_headers(self):

        pass

    def make_post_request(self, url, data, headers):
        response = requests.post(url, data, headers=headers)
        return response

    def make_get_request(self, url, data):
        response = requests.get(url, data)
        return response

class Source2Client:

    def get_domain(self):

        pass

    def get_endpoint(self):

        pass

    def get_headers(self):

        pass

    def make_post_request(self, url, data, headers):
        response = requests.post(url, data, headers=headers)
        return response

    def make_get_request(self, url, data):
        response = requests.get(url, data)
        return response

    def call_stored_procedure(self, query):

        pass

    def run_query(self, query):

        pass

class BaseSync:

    def convert_data_to_serialized_objects(self, data, serializer, many=True):
        db_object, db_object_list = {}, []
        for i in data:
            for column, value in i.items():
                db_object = {**db_object, **{column: value}}
            db_object_list.append(db_object)

        schema = serializer(many=many)
        m = schema.dump(db_object_list)
        return m.data

    def get_serialized_data(
        self,source=None, query=None, proc=None, serializer=None, many=True, proc_kwargs={},
        endpoint=None, method=None, data=None, headers=None
    ):
        if source == "source1":
            client = Source1Client()
        if source == "source2":
            client = Source2Client()
        if proc:
            formatted_query = proc.format(**proc_kwargs)
            raw_data = cllient.call_stored_procedure(formatted_query)
        if query:
            raw_data = client.run_query(query)
        else:
            if method == "get":
                raw_data == client.make_get_request(endpoint, data)
            if method == "post":
                raw_data == client.make_post_request(endpoint, data, headers)

        serialized_data = self.convert_data_to_serialized_objects(
            raw_data, serializer, many=many
        )
        return serialized_data

class DataSync(BaseSync):

    def sync_source1_data():

        source1_data = self.get_serialized_data(source="source1", endpoint="source1url/path")

        # other operations

    def sync_source2_data():

        source1_data = self.get_serialized_data(source="source2", endpoint="source1url/path")

        # other operations

In my code get_serialized_data is using multiple if-else cases, which will make code dirty and hard to read if more sources are added. Also, it has too many parameters, which is against clean code principles.

What can be a better implementation to make code cleaner, maintainable and readable?

Use __init__ to handle bunch of arguments, then your self will take of passing arguments to your respective definition - that's the good way to use OOP in python.

class Foo:
    def __init__(self, value_a, value_b):
        self.a = value_a
        self.b = value_b

    def func(self):
        pass

To avoid multiple if else you can have list or dict and from there you can access.
Hope this helps !!


C++ Heap Sort In C++14 Realized I have never implemented heap sort.

So here is my first attempt:

#include <iterator>
#include <tuple>

/*
0   => 1 2
1   => 3 4
2   => 5 6
3   => 7 8
4   => 9 10
5   => 11 12
6   => 13 14

P   => P*2 + 1, P*2 + 2
C   => (C-1)/2
*/

template<typename I>
class HeapSorter
{
    I getParent(I root, I child)
    {
        std::size_t dist = std::distance(root, child);
        return root + (dist - 1) / 2;
    }

    std::tuple<I, I>  getChildren(I root, I parent)
    {
        std::size_t dist = std::distance(root, parent);
        I left  = root + (dist * 2 + 1);
        I right = root + (dist * 2 + 2);
        return {left, right};
    }

    bool swapLargestValueWithRoot(I& root, I left, I right)
    {
        using std::swap;
        if (*root >= *left && *root >= *right) {
            return true;
        }
        I& swapSrc = (*left >= *right) ? left : right;

        swap(*root, *swapSrc);
        root = swapSrc;
        return false;
    }

    void siftDown(I root, I begin, I end)
    {
        I parent    = begin;
        I left;
        I right;
        std::tie(left, right) = getChildren(root, parent);
        while(left < end) {

            if (swapLargestValueWithRoot(parent, left, right == end ? left : right)) {
                break;
            }
            std::tie(left, right) = getChildren(root, parent);
        }
    }

    void heapify(I begin, I end)
    {
        I child   = end - 1;
        if (child == begin) {
            return;
        }
        I parent  = getParent(begin, child);
        for(;parent != begin;--parent) {
            siftDown(begin, parent, end);
        }
        siftDown(begin, begin, end);
    }
    public:
        void operator()(I begin, I end)
        {
            static_assert(std::is_same<typename std::iterator_traits<I>::iterator_category, std::random_access_iterator_tag>::value, "For efficiency; Only support random access Iterator");
            if (begin == end) {
                return;
            }
            heapify(begin, end);
            for(auto loop = end - 1;loop != begin; --loop) {
                std::iter_swap(begin, loop);
                siftDown(begin, begin, loop);
            }
        }
};

template<typename I>
void heapSort(I begin, I end)
{
    HeapSorter<I>  sorter;
    sorter(begin, end);
}

Usage Example:

#include <algorithm>
#include <iostream>

int main()
{
    int data[] = { 5,6,3,8,9,1,4,0,2,3,6,1,7,8,9};

    heapSort(std::begin(data), std::end(data));

    std::copy(std::begin(data), std::end(data),
              std::ostream_iterator<int>(std::cout, ","));
}

Well, strictly speaking your code has UB because getChildren(...) tries to create iterators to both child-nodes, even if they are beyond the end-iterator.
Some iterators and containers are more forgiving than others, as are implementations generally...

You forgot the include for std::swap and std::iter_swap: <algorithm>.
Also for std::is_same: <type_traits>.
Both obviously happen to be included by your current includes.

You might want to use std::iter_swap consistently, look in swapLargestValueWithRoot.


Caesar cipher brute force I have code that uses the brute force technique to find the message to a Caesar cipher. The program decrypts the message using different keys and then checks whether the resulting words are contained in a file called 'wordlist.txt'. if they are, it returns only that result.

from collections import namedtuple
Keycode = namedtuple('Keycode', 'key code')

def picks(filename):
    with open(filename) as f:
        lines = [line.strip() for line in f]
    return lines

message = 'vlr alkq exsb ql qefkh xylrq qexq exex.'
LETTERS = 'abcdefghijklmnopqrstuvwxyz'
result = []
for key in range(len(LETTERS)):
    translated = ''
    for symbol in message.lower():
        if symbol in LETTERS:
            num = LETTERS.find(symbol)
            num = num - key
            if num < 0:
                num = num + len(LETTERS)
            translated += LETTERS[num]
        else:
            translated += symbol
    result.append(Keycode(key, translated))

for item in result:
    d = item.code.split()
    for word in d:
        if word in picks('wordlist.txt'):
            print('Code : {0:s}\nKey  : {1:}'.format(item.code, item.key))
            break

The code that I have does the job but it takes time and the code is not clean. Is there a way to make the code a bit cleaner? I am new to Python and haven't started on classes, so I cant use those (although it would have made my job easier).

Split your code into small units

If you split you split your code, (most of the time) you automatically make it easier to read and to test. Also, it allows you to use Python syntactic sugar like list comprehension much more easily.

Modulo operator

As suggested in the comments, the % operator allows you to write things in a smarter way.

Better than abcdef...z

You can use string.ascii_lowercase (after importing string) instead of defining it yourself.

Use join instead of string concatenations

As adviced by the Python Style Guide called PEP 8 :

  In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.

This is very straightforward once you have a function to encode a single letter.

At this stage, the code looks like :

def caesar_letter(symbol, key):
    if symbol in LETTERS:
        return LETTERS[(LETTERS.find(symbol) - key) % len(LETTERS)]
    else:
        return symbol

def caesar(msg, key):
    return ''.join(caesar_letter(l, key) for l in msg.lower())

result = [Keycode(key, caesar(message, key)) for key in range(len(LETTERS))]

Another tips

Instead of generating all possible strings only to stop once you've found the one you want, you could generate them at you go. If the first string is the one you want, you'll avoid most of the work.

for key in range(len(LETTERS)):
    code = caesar(message, key)
    d = code.split()
    for word in d:
        if word in picks('wordlist.txt'):
            print('Code : {0:s}\nKey  : {1:}'.format(code, key))
            break

if __name__ == "__main__":

You should move your code actually doing stuff behind an if __name__ == "__main__": guard. I'll let you read more about this.


Menu for purchasing tequila and whiskey I would like to hear some feedback about style on my program, and which one is better "do while" or "while loop" to run my program.

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

#define Tequila 20
#define Whiskey 25

int main()
{

    int choice = 0;
    int bottle1= 0;
    int bottle2= 0;
    int final_total= 0;
    int total1 =0;
    int total2 =0;

    do{
        printf("\tMain Menu MK liquor Store\n");
        printf(" \tEnter your choice: \n");
        printf("\t 1-  Buy Tequila Jose Cuervo\n");
        printf("\t 2-  Buy Whiskey Jack Daniels\n");
        printf("\t 3-  Quit\n");

        scanf("%d", &choice);

        switch(choice)
        {
            case 1:
                printf("how many bottles of Tequila would you like\n");
                scanf("%d", &bottle1);
                printf("so far you got %d bottles in your basket \n", bottle1);

                break;
            case 2:
                printf("how many bottles of Whiskey would you like\n");
                scanf("%d", &bottle2);
                printf("so far you got %d bottles in your basket\n", bottle2);

                break;
            case 3:
                total1=bottle1 * Tequila;
                total2= bottle2 * Whiskey;
                final_total = total1+total2;
                printf("You obtained %d bottles of Tequila and %d of Whisky\n", bottle1,bottle2);
                printf("Your total  is %d dollars\n",final_total);

                break;
            default:

                printf("ERROR INVALID OPTION.\n\n");

                break;

        }

    }while (choice != 3);
        return 0;

    }

I would like to hear some feedback about style on my program,

The vertical spacing is excessive.

Odd separation example: blank lines between case code printf("so far you got %d bottles in your basket\n", bottle2); and break; misleads code blocks.  Consider instead;

        case 2:
            printf("how many bottles of Whiskey would you like\n");
            scanf("%d", &bottle2);
            printf("so far you got %d bottles in your basket\n", bottle2);
            break;

        case 3:

{ at line end or next line:  Stay consistent

do{
...
    switch(choice)
    {                  // why here vs above line

I'd expect following to be less indented.

       return 0;

It is apparent code is not written using an auto formatter and that is the biggest style problem.  Any style worth using will match an auto formatter.  Manually formatting is not productive and too inconsistent.

  and which one is better "do while" or "while loop" to run my program.

Use of do() is OK here as the loop should always execute at least once.  Some style guides eschew do().  As will such styles issues, follow your group's coding rules.

Style aside, code not checking the result of an input function like scanf("%d", &choice); is weak.

// better
if (scanf("%d", &choice) != 1)  {
  break;
}


Transforming elements of std containers from other std containers Problem

In this HackerRank problem we are asked to rotate the elements of a matrix in the following way:

Example Input and Output

First and second entry specify the size of the matrix and third entry how many times it has to be rotated. As an example, the following input:

4 4 2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

would produce the following output:

3 4 8 12
2 11 10 16
1 7 6 15
5 9 13 14

Solution

My idea was to rotate these rings.

#include <vector>
#include <iostream>
#include <algorithm>

using Matrix = std::vector<std::vector<int>>;

void rotate_mat (Matrix &mat, int r){
    auto m = mat.size(); // Number of rows
    auto n = mat[0].size(); // Number of columns
    auto n_rings = std::min(m,n)/2; // Number of rings
    for(auto ring_i=0; ring_i<n_rings; ++ring_i){
        // The elements of the ring are stored sequentially
        // in v_ring so it can be rotated with std::rotate
        std::vector<int>  v_ring;
        // v_ring_ptr points to the original places in the matrix,
        // so the rotation of v_ring can be assigned back to the matrix
        std::vector<int*> v_ring_ptr;
        // Top side of the ring
        for(auto j=ring_i; j<=(n-1)-ring_i; ++j) {
            v_ring.push_back(mat[ring_i][j]);
            v_ring_ptr.push_back(&mat[ring_i][j]);
        }
        // Right side of the ring
        for(auto i=ring_i+1; i<=(m-1)-ring_i; ++i) {
            v_ring.push_back(mat[i][(n-1)-ring_i]);
            v_ring_ptr.push_back(&mat[i][(n-1)-ring_i]);
        }
        // Bottom size of the ring
        for(auto j=(n-1)-ring_i-1; j>ring_i; --j) {
            v_ring.push_back(mat[(m-1)-ring_i][j]);
            v_ring_ptr.push_back(&mat[(m-1)-ring_i][j]);
        }
        // Left size of the ring
        for(auto i=(m-1)-ring_i; i>ring_i; --i) {
            v_ring.push_back(mat[i][ring_i]);
            v_ring_ptr.push_back(&mat[i][ring_i]);
        }

        std::rotate(v_ring.begin(),v_ring.begin()+r%v_ring.size(),v_ring.end());
        // Update the rotated values in the original matrix
        for (auto i=0; i<v_ring.size(); ++i){
            *v_ring_ptr[i] = v_ring[i];
        }
    }
};

Matrix read_matrix(int m, int n) {
    Matrix mat;
    mat.reserve(m);
    for(auto i=0; i<m; ++i) {
        mat.push_back(std::vector<int>{});
        mat[i].reserve(n);
        for(auto j=0; j<n; ++j) {
            int x; std::cin >> x;
            mat[i].push_back(x);
        }
    }
    return mat;
};

void print_matrix(Matrix &mat){
    for (auto& i : mat){
        for (auto& j : i) {
            std::cout << j << " ";
        }
        std::cout << "\n";
    }
};

int main() {
    int m,n; std::cin >> m >> n;
    int r; std::cin >> r;

    auto mat = read_matrix(m,n);
    rotate_mat(mat,r);
    print_matrix(mat);

    return 0;
}

Questions

My main problem is that I would like to avoid having the v_ring copy and this part:

for (auto i=0; i<v_ring.size(); ++i){
    *v_ring_ptr[i] = v_ring[i];
}

Is there a way to store references to the content of the original matrix so the transformation in the constructed rings would automatically be reflected? I tried with std::reference_wrapper. It almost works with that, I can modify the elements in the ring for example with ++ operator, but I cannot make assigments, nor std::rotate has any effect on them.

Any ideas? I'm also interested in any other approach that could come to your mind! I thought this way was easy to express in code

Some things to note :

As you said there are std::min(m,n)/2; rings.
the ring R(r, p) has 2*(r+p-2) elements.
the top left of the ring has always coordinates (x,x). This is visible in your code :) j = ring_i; v_ring.push_back(mat[ring_i][j]);
Your code is using a relatively efficient amount of memory for the in-place transformation, and running in O(m*n) time, which is the best possible.
A performance improvement will be to use a single vector for the data in the matrix such that m(x,y) = m.data[x * cols + y]

Can we do it differently ?

Given the local coordinates system where (0, 0) is the top left of the ring

A coordinate (i,j), 0<=i<w, 0<=j<h, j == 0 || i == 0 on a side of a ring, can be moved by one position using the function

std::pair<int, int>
rotated_local_next(int i, int j, int w, int h)
{
   if(j == 0) //top , special case top-right
   {
        return i == w-1 ? std::make_pair(i, ++j) : std::make_pair(++i, j);
   }
   if(i == w-1) //right, special case bottom-right
   {
        return j == h-1 ? std::make_pair(--i, j) : std::make_pair(i, ++j);
   }
   if(j == h-1) //bottom, special case bottom-left
   {
        return i == 0 ? std::make_pair(i, --j) : std::make_pair(--i, j);
   }
   if(i == 0) //left, special case top-left
   {
        return j == 0 ? std::make_pair(++i, j): std::make_pair(i, --j);
   }

   // cannot happen
   throw std::exception{};
}

You can now implement in matrix coordinates

std::pair<int, int>
rotated_matrix_next(int x, int y, int ring_i, int height, int width )
{
     auto local_point = rotated_local_next(x-ring_i, y-ring_i, width-2*(ring_i), height-2*(ring_i));
     return std::make_pair(local_point.first + ring_i, local_point.second + ring_i);
}

All you need to do now is to implement iterators satisfying MoveAssignable and MoveConstructible. The beginning of your ring is the element at positing ring, ring, which is also the end of the ring.

struct RingView
{
    //ring start at 0
   RingView(std::vector<std::vector<int>>& mat, int ringnumber)
   : matrix(mat)
   , rows(mat.size())
   , cols(mat[0].size())
   , ring(ringnumber)
   {}

   std::vector<std::vector<int>>& matrix;
   int rows;
   int cols;
   int ring;

    class ring_iterator : public std::iterator<std::forward_iterator_tag, int>
    {
    public:

        ring_iterator(RingView* v = nullptr, int xpos = 0, int ypos = 0)
        : view(v)
        , x(xpos)
        , y(ypos)
        {}

        ring_iterator(const ring_iterator& other) = default;
        ring_iterator(ring_iterator&& other) = default;
        ring_iterator& operator =(ring_iterator const&) = default;
        ring_iterator& operator=(ring_iterator&&) = default;
        virtual ~ring_iterator() = default;

        RingView* view;
        int x;
        int y;

        // Forward
        ring_iterator& operator++() {
            auto posnext = rotated_matrix_next(x, y, view->ring, view->cols, view->rows);

            x = posnext.first;
            y = posnext.second;
            return *this;
        }

        ring_iterator operator++(int) {
            auto posnext = rotated_matrix_next(x, y, view->ring, view->cols, view->rows);
            ring_iterator next_iter = *this;
            next_iter.x = posnext.first;
            next_iter.y = posnext.second;
            return next_iter;
        }

        bool operator==(const ring_iterator& other) const {
            if(view == nullptr ){
                return other.view == nullptr;
            }
            return view->ring == other.view->ring && x == other.x && y == other.y;
        }

        bool operator!=(const ring_iterator& other) const {
            return !(*this == other);
        }

        // usually required
        int& operator*() {
            return view->matrix[x][y];
        }
        int* operator->() {
            return &(view->matrix[x][y]);
        }
    };

    ring_iterator begin()
    {
        return ring_iterator(this, ring, ring);
    }

    ring_iterator end()
    {
        return begin();
    }

    int size() const
    {
        return 2*(rows+cols -2) - 4 * ring;
    }
};

Now you can rotate the matrix using the view. To be able to rotate in both directions (positive for clockwise, negative counter-clockwise) we use

r' = (r % view.size() + view.size()) % view.size();

void rotate_mat (Matrix &mat, int r){
    auto n_rings = std::min(mat.size(),mat[0].size())/2; // Number of rings
    for(auto ring_i=0; ring_i<n_rings; ++ring_i){
        RingView view(mat,ring_i);
        int r_modulo = (r % view.size() + view.size()) % view.size();
        auto next_location = view.begin();
        std::advance(next_location, r_modulo);
        std::rotate(view.begin(),next_location,view.end());
    }
}

Full code : https://ideone.com/I3vg5v


Fetch an array result set using a mysqli wrapper class I have a PHP class:

<?php
//connectionclass.php
class connectionclass{
public $conn;
public $warn;
public $err;

function __construct(){
  $this->connect();
}

private function connect(){
  $this->conn = @ new mysqli('localhost', 'sever_user', 'user_password');
    if ($this->conn->connect_error) {
      $this->conn = FALSE;
      $this->warn = '
Failed to connect database! Please try again later';
     }
}

public function get_data($qry){
 $result = $this->conn->query($qry);
    if ($result->num_rows>=1) {
        while($row=$result->fetch_assoc()){
           $rows[] = $row;
        }
        return $rows;
    } else {
        $this->err = $this->conn->error;
        return FALSE;
    }
}

}
?>

and a PHP page:

<?php
//login.php
include('/include/connectionclass.php');
$db = new connectionclass();

$query = "SELECT * FROM USERS WHERE user_country='India'";
$data = $db->get_data($query);
  $rownum = count($data);
  for($i=0;$i<$rownum;$i++){
     echo $data[$i]['name'].'- '.$data[$i]['age'].'
';
  }
?>

Is there any idea for an easier way to iterate $data in the PHP page?

First, you can use mysqli_result::fetch_all in your connectionclass::get_data() instead of manually looping and building the result array.

Second, you can use foreach to easily iterate through results


Simple flex-based lexer I am trying to learn flex and have created this simple program. The rule for comments works correctly for single line comments such as:

// this is a comment

and this:

/* this is also a comment */

My code:

ID [A-Z][A-Za-z0-9]
KEYWORD if|else|then|for|fi|loop|pool|proc|func
OPERATOR "+"|"-"|"/"|"*"|"&"|"%"
PUNCTUATION ":"|","
%%
{ID} printf("An Id found:%s\n",yytext);
{KEYWORD} printf("An Keyword found:%s\n",yytext);
{OPERATOR} printf("An Operator found:%s\n",yytext);
{PUNCTUATION} printf("An Punctuation found:%s\n",yytext);
[/][/].*

"/*".*"*/"

%%
int yywrap(){
  return 1;
}
main(){
  yylex();
}

I'd be interested in comments on this and particularly ways to improve the code, such as for being able to detect multi-line comments.

The code looks OK for what it does so far, but there are some things you might want to do to improve it:

Always use {} for production rules

It's not technically wrong to simply have printf(...) to the right of a rule, but when your lexer gets more complex (and when you start also using a parser) you may find it easier to troubleshoot if you always use {} to enclose production rules -- even empty ones.

Think about explicitly handling whitespace

It's very common for a parser to need to ignore whitespace. If that's the case, it's usually good to do so explicitly with a rule just above the error-handling rule(s) I mention below.

[ \t\n]+   { /* ignore whitespace */ }

Consider a "catch-all" rule for illegal tokens

Right now, pretty much any random character will be accepted.  This might be fine, but especially while you're learning, you may find it useful to put a catch-all rule at the bottom of your list of rules:

.   { printf("Bad character: %s\n", yytext); }

Consider adding support for multiline comments

As your original (pre-edit) code had it, handling multiline comments is different but not too difficult.  You can add this to your definitions (the first part of a flex file):

%x c_comment

Then add these rules to the rules section (second part of a flex file):

"/*"   { BEGIN(c_comment); }
<c_comment>[^*]*        { }
<c_comment>"*"+[^*/]*   { }
<c_comment>"*/"         { printf("Ignored a multiline comment\n"); BEGIN(INITIAL); }

This defines a start condition called c_comment and switches into that condition when it finds the opening pair of characters for a comment.  The next rule ignores everyting that is not a * character. The next line ignores all * characters that are not followed by a /.  The point to these two rules is to match as many characters as possible.  For performance reasons, you would generally want to write your lexer so that it matches strings that are as long as possible for each rule.  This helps the lexer go faster.

Finally, the last rule finds the closing pair of characters and switches back into the initial context.  You will also often see BEGIN(0) for that -- the statements are identical in function, but I prefer the more verbose BEGIN(INITIAL) form because I think it's easier to understand.


Solving hard 3rd-grade math This is a problem proposed by Vietnamese for a 3rd-grade student international contest in Malaysia, 2017. You have to find 3 numbers with conditions:

[][][][] - [][][][] - [] = 2017.

Each digit in each cell range from 1 to 9 and they must be different each other.

I can't solve by hand, so I have made a program to find results.  My code works but is too long, so does anyone have a shorter way?

public class Third_gradeProblem {
public static void main(String[] args) {
int a,b,c,d,e,f,g,h,i;
int so1,so2,so3;
for(a=1;a<=9;a++) {
    for(b=1;b<=9;b++) {
        for(c=1;c<=9;c++) {
            for(d=1;d<=9;d++) {
                for(e=1;e<=9;e++) {
                    for(f=1;f<=9;f++) {
                        for(g=1;g<=9;g++) {
                            for(h=1;h<=9;h++) {
                                for(i=1;i<=9;i++) {
                                    so1=a*1000+b*100+c*10+d;
                                    so2=e*1000+f*100+g*10+h;
                                    so3=i;
                                    if((so1-so2-so3==2017)&&(a!=b)&&(a!=c)&&
(a!=d)&&(a!=e)&&(a!=f)&&(a!=g)&&(a!=h)&&(a!=i)&&(b!=c)&&(b!=d)&&(b!=e)&&
(b!=f)&&(b!=g)&&(b!=h)&&(b!=i)&&(c!=d)&&(c!=e)&&(c!=f)&&(c!=g)&&(c!=h)&&
(c!=i)&&(d!=e)&&(d!=f)&&(d!=g)&&(d!=h)&&(d!=i)&&(e!=f)&&(e!=g)&&(e!=h)&&
(e!=i)&&(f!=g)&&(f!=h)&&(f!=i)&&(g!=h)&&(g!=i)&&(h!=i)) {
                                        System.out.println(so1+" "+so2+"
"+so3);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

}
}

}

Results:

4613 2587 9;
4613 2589 7;
7412 5386 9;
7412 5389 6;
7421 5396 8;
7421 5398 6;

The main performance problem of your code is that you check for duplicate digits only in the innermost loop, although a collision between e.g. a and b can be detected already in the second loop.

This way you generate 387420489 digit combinations and throw away 99.9% of them (it's only 362880 permutations of 9 digits). Moving the duplicates checks to the outermost place possible can potentially speed up your program by a factor of 1000.

And there might be better algorithms, but on Code Review we concentrate on improving your original code instead of inventing something new.


Simple landing page using Bootstrap I have written a simple landing page in Twitter Bootstrap. It works fine, I just want to know if my code is written in a "good-practice" way.

<!DOCTYPE html>

  <title>SigmaCubes - Home</title>
  <link href="favicon.ico" rel="shortcut icon" />

  <meta charset="utf-8">
  <meta content="IE=edge" http-equiv="X-UA-Compatible">
  <meta name="author" content="Julian Lachniet" />
  <meta name="description" content="Various HTML and JavaScript projects." />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />

  <link rel="stylesheet" href="lib/bootstrap.min.css">

        About

        CubeSolver

        Projects

Various HTML and Javascript projects.

SigmaCubes.com is the best website on the internet, and the owner of CubeSolver.

Any suggestions?

Good start. I would like to add a few minor things:

Character encoding

As a good practice, the character encoding should be the first element of the head section - or at least it should come before the title element:

<meta charset="utf-8">
<title>SigmaCubes - Home</title>

  In order for all browsers to recognize a  declaration, it must be

  Within the  element,
  Before any elements that contain text, such as the <title> element, AND
  Within the first 512 bytes of your document, including DOCTYPE and whitespace

From Google Code Archive doctype-mirror - MetaCharsetAttribute.wiki

Be consistent

In HTML5 void elements can have an optional / before the closing >. As it seems that you prefer to add this slash, use it everywhere and not only on some elements, like here:

<meta charset="utf-8">
<meta content="IE=edge" http-equiv="X-UA-Compatible">
<meta name="author" content="Julian Lachniet" />
<meta name="description" content="Various HTML and JavaScript projects." />

Here are some more information about this topic: HTML 5: Is it
,
, or
?

Valid HTML

Images have a mandatory alt-attribute:

You should add this attribute to all img elements. It will not only help people using screen readers to better understand your website, it might also improve SEO.

For more details, see Wikipedia: https://en.wikipedia.org/wiki/Alt_attribute.

Indentation

Try to indent elements, if possible.

… is easier to conceive as:

Semantics

Your main navigation looks fine. However, the section starting with
 looks a bit like divitis.

Learn about HTML5 semantics and how to structure the content of your website. Here're some related articles on w3.org to get started:

3.2.1. Semantics
4.3. Sections
4.5. Text-level semantics

Inline styles

Try to avoid inline styles. This might work for a small page like this, but will get complicated as your project grows.

Instead add a custom CSS file in addition to Bootstrap, where you expand existing styles and add new classes as well.


How to re register dynamic scripts registered with ClientScriptManager in asp dot net using session was bad idea Following the normal pattern of adding inline scripts to gridview row/s is a bad practice it used to work like below

 protected void CustomersGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        switch (e.Row.RowType)
        {
            case DataControlRowType.DataRow:
                DataRowView drv = (DataRowView)e.Row.DataItem;
                if (drv != null)
                {
                    string sKey = drv["Id"].ToString();                                e.Row.Attributes.Add("onclick","location.href='manage.aspx?="+sKey+"'");
                }
                break;
        }
    }

hence i switched over to event registration pattern which worked like below

protected void CustomersGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        switch (e.Row.RowType)
        {
            case DataControlRowType.Header:
                StringBuilder _sbDynamicScript = new StringBuilder();
                _sbDynamicScript.AppendLine("Sys.Application.add_load(function(){");
                _sbDynamicScript.AppendLine("try{");
                break;
            case DataControlRowType.DataRow:
                DataRowView drv = (DataRowView)e.Row.DataItem;
                if (drv != null)
                {
                    string sKey = drv["Id"].ToString();
                    e.Row.Attributes.Add("id", randomNumber);
                    _sbDynamicScript.AppendLine("if($get('" + randomNumber + "'))$addHandler($get('" + randomNumber + "'),'click',function(evnt){location.href='manage.aspx?id='="+ sKey +"'})");
                }
                break;
            case DataControlRowType.Footer:
                _sbDynamicScript.AppendLine("}catch(err){alert(err.message)}})");
                if (!Page.ClientScript.IsStartupScriptRegistered(GetType(), "customerapp"))
                {
                    Page.ClientScript.RegisterStartupScript(GetType(), "customerapp", _sbDynamicScript.ToString(), true);
                }
                Session["clientScript"] = _sbDynamicScript.ToString();
                break;
        }
    }

notice rowType is used to create dynamic script. Here's something that's happening up there

1.add a random number as ID for the gridview row

2.then add a click event handler using the asp.net ajax

make the make navigate away on click

Bug's ahoy:

Notice that in footer template i have put that script into session, that was my mistake. You see the scripts registered using registerstartup script are not persisted on postbacks and have to be re-registered. i have put a check on PageLoad to do below

 if (!Page.ClientScript.IsStartupScriptRegistered(GetType(), ""))
            {
                Page.ClientScript.RegisterStartupScript(GetType(), "customerapp", Session["clientScript"].ToString(), true);
            }

  notice the script is registered from
  session!! Well it happens some times
  that the Gridview records are changed
  by postback. But since session has
  already the key in it, the
  rowdatabound event script fails to get
  registered with new script. So what do
  i do in this situation. Can i get some
  other way to persist the script and
  make it run whenever gridview binds
  again

btw the script registered will look like below

Sys.Application.add_load(function () {
    try {
        if ($get('ElSxrM4myH4%3d')) {
            $addHandler($get('ElSxrM4myH4%3d'), 'click', function (evnt) {})
        }
    } catch (err) {
        alert(err.message)
    }
})

Would it not be better to build a generic script to handle all row scripting requirements, and include once per page? You'll end up with a cleaner end script, and your page footprint will be a lot smaller. You'll also benefit from the browser's resource caching.

Using jQuery, you could achieve something like:

$(function() {
    $("tr.needEvent td").live(function() {
        // Event handler code goes here.
    });
});

where tr.needEvent is a class appended to the <tr> used to wrap a row. If you aren't using tables, this could be used the same way with <div> or any other container element. The important thing is, using .live() we can run the code once, and any other elemnets added to the page that match that selector, will be bound to the event handler automatically.

The use of $(function() { is the jQuery equivalent of Sys.Application.add_load(function() {


Guess My Number, Classic Edition I am learning Python at present, from several books. I am new to programming and I need assistance with knowing when my code is written with good form and style - I want to ingrain the habit of writing good clean code, which would be accepted as thus by other programmers. This is a code example from the book Python Programming for the Absolute Beginner by Michael Dawson, which I have altered in several ways - a game which picks a random number and asks the player to guess that number:

# Alex Grattan
# 8/10/14

# Guess My Number
#
# The computer picks a random number between 1 and 100
# The player tries to guess it and the computer lets
# the player know if the guess is too high, too low
# or right on the money

import random

print("\tWelcome to 'Guess My Number'!")
print("\nI'm thinking of a number between 1 and 100.")
print("Try to guess it in as few attempts as possible.\n")

# set the initial values
the_number = random.randint(1, 100)
guess = int(input("Take a guess: "))
tries = 1

# guessing loop
while guess != the_number:
    if guess > the_number:
        print("Lower...")
    else:
        print("Higher...")

    guess = int(input("Take a guess: "))
    tries += 1
    if tries == 5:
        print "You failed to guess in time!"
        break
    if guess == the_number:
        print("You guessed it! The number was", the_number)
        print("And it only took you", tries, "tries!\n")

raw_input("\n\nPress the enter key to exit.")

The code works, however, I feel it is slightly 'bloated' and messy. How would a more experienced programmer change my code?

Mixing Python 2 and 3

The program is correct in neither Python 2 nor Python 3.

Your program fails to run at all in Python 3, due to the lack of parentheses when calling

print "You failed to guess in time!"

Also, the raw_input() function does not exist in Python 3.

On the other hand, it's not quite correct under Python 2 either.  These print statements

print("You guessed it! The number was", the_number)
print("And it only took you", tries, "tries!\n")

would be interpreted as requests to print tuples… complete with parentheses and commas.

Initialization

The number of allowed guesses, 5, is buried in the middle of your program, and should be defined in an obvious place near the top.

The bounds, 1 and 100, are each hard-coded twice.  That is a maintenance pitfall, should you ever need to change the upper bound.  Again, these special numbers should be defined just once in an obvious place.

Loop

The "Take a guess" prompting statement is written twice.  It should be moved inside the loop, at the top of the loop.

@MasayukiFujita and @MathiasPanda have the right idea, I think, to use the count rather than the correctness as the loop condition.  I would go a step further and suggest that counting loops in Python would be more idiomatically written using for counter in range(…).

To distinguish between the winning and losing condition without using a boolean variable or retesting the correctness of the guess, you can take advantage of an obscure Python language feature: an else clause on a loop.  The else clause is executed only when the loop terminates "naturally", rather than due to a break.

Newline management

You'll have a better time printing nice output if you make a habit of always putting your newlines at the end of print statements.

Suggested solution

Here is a program that works in both Python 2 and Python 3.

import random

BOUNDS = (1, 100)
TRIES_ALLOWED = 5

the_number = random.randint(*BOUNDS)

print("\tWelcome to 'Guess My Number'!\n")
print("I'm thinking of a number between %d and %d." % BOUNDS)
print("Try to guess it in as few attempts as possible.\n")

for tries in range(TRIES_ALLOWED):
    guess = int(input("Take a guess: "))

    if guess > the_number:
        print("Lower...")
    elif guess < the_number:
        print("Higher...")
    else:
        print("You guessed it! The number was %d" % (the_number))
        print("And it only took you %d tries!\n\n" % (tries + 1))
        break
else:
    print("You failed to guess in time!\n\n")

# Admittedly a contorted way to write a statement that works in both Python 2 and 3...
try:
    input("Press the enter key to exit.")
except:
    pass


Mergesort and validation I have written an implementation of a Mergesort in Python3. An Ideone with the implementation is available. Any suggestions for improvement or any criticisms?

def merge(a, aux, lo, mid, hi):
    assert isSorted(a, lo, mid)
    assert isSorted(a, mid+1, hi)

    for k in range(lo, hi+1):
        aux[k] = a[k]

    i, j = lo, mid + 1
    for k in range(lo, hi+1):
        print("i = ",i, ", j = ",j)
        if i > mid:
            a[k] = aux[j]
            j += 1
        elif j > hi:
            a[k] = aux[i]
            i += 1
        elif aux[i] < aux[j]:
            a[k] = aux[i]
            i += 1
        else:
            a[k] = aux[j]
            j += 1
    assert isSorted(a, lo, hi)

def sort(a, aux, lo, hi):
    if (lo >= hi): return a
    mid = math.floor(lo + (hi-lo) / 2)

    sort(a, aux, lo, mid)
    sort(a, aux, mid+1, hi)
    merge(a, aux, lo, mid, hi)

def merge_sort(a):
    aux = [0] * len(a)
    sort(a, aux, 0, len(a)-1)
    assert isSortedArray(a)

def isSorted(a, lo, hi):
    for i in range(lo, hi):
        if a[i+1] < a[i]:
            return False
    return True

def isSortedArray(a):
    for i in range(0, len(a)-1):
        if a[i+1] < a[i]:
            return False
    return True

You could avoid typing +1 and -1 in a few places by using inclusive-exclusive ranges, like 200_success nicely explained answering to your other question.
isSortedArray should call isSorted instead of repeating the same code.
Instead of math.floor(lo + (hi-lo) / 2) you could use integer division (lo + hi) // 2 so you don't need to import math.
Passing around aux just to have a place for temporary data in merge seems like an unnecessary complication. Instead you could just take two slices from a and merge them back into a.


Unit Test case to check if localstorage is empty once I logout of the Web app I am trying to clear my localstorage when I am logging out of the application. I want to write a unit test case in Jasmine to check if this task is performed when logout function is run. I am writing test cases for the first time so got stuck in the approach.

In my compoment.ts file I have a logout function:

logout() {
    location.href = "/";
     localstorage.clear();
}

spec.ts file

beforeEach(function () {
        var store = {};
        spyOn(localStorage, 'getItem').andCallFake(function (key) {
            return null;
        });
    });

I don't know if this is a correct approach to write the test case for this particular requirement or which one among unit or integration test cases is actually valid for this situation.

If you are using any I/O (in this case, local storage), you must have fallen into an integration test.

A unit test could be that when logout is executed, the call to
clearing the local storage is made (using an spy on localStorage).
An integration test could be that you have data in the local storage and after you have logged out, you don't.