Different payment details in a common list, to be casted I need to be able to access a number of different payment methods in a common list. They can be different methods - credit card, cheque, direct debit etc. The only common attributes are the payment method id and PaymentMethodEnum. I would then be casting the payment method to it's appropriate type to get the extended properties. Is this code arrangement the best way to achieve that?

Update:
I've added the enums. The usage for this is an MVC Website, and these payment details are effectively read only. The website shows different options based on the current payment method, and the other available methods that belong to a customer.

public class PaymentDetailBase
{
    public PaymentDetailBase(string id, PaymentMethodEnum paymentMethod)
    {
        this.Id = id;
        this.PaymentMethod = paymentMethod;
    }

    public string Id { get; }

    public PaymentMethodEnum PaymentMethod { get; }
}

public class CardDetail : PaymentDetailBase
{
    public CardDetail(string id, PaymentMethodEnum paymentMethod, string last4, DateTime expiry, PaymentCardTypeEnum cardType) : base(id, paymentMethod)
    {
        this.Last4 = last4;
        this.Expiry = expiry;
        this.CardType = cardType;
    }

    public string Last4 { get; }

    public DateTime Expiry { get; }

    public PaymentCardTypeEnum CardType { get; }
}

public class DirectDebitDetail : PaymentDetailBase
{
    public DirectDebitDetail(string id, PaymentMethodEnum paymentMethod, string accountName, string routingNumber, string bankAccount, DirectDebitAccountTypeEnum accountType) : base(id, paymentMethod)
    {
        this.AccountName = accountName;
        this.RoutingNumber = routingNumber;
        this.BankAccount = bankAccount;
        this.AccountType = accountType;
    }

    public string AccountName { get; }

    public string RoutingNumber { get; }

    public string BankAccount { get; }

    public DirectDebitAccountTypeEnum AccountType { get; }
}

[Flags]
public enum PaymentMethodEnum
{
    [Description("NONE")]
    None        = 0,

    [Description("Credit Card")]
    CreditCard  = 1 << 0,

    [Description("Direct Debit")]
    DirectDebit = 1 << 1,

    [Description("Check")]
    Cheque      = 1 << 2,

    [Description("Invoice")]
    Invoice     = 1 << 3,

    [Description("Money Order")]
    MoneyOrder  = 1 << 4,

    [Description("Paper Invoice")]
    PaperInvoice = 1 << 5
}

public enum PaymentCardTypeEnum
{
    [Description("Unknown")]
    Unknown,

    [Description("AMEX")]
    Amex,

    [Description("MASTERCARD")]
    MasterCard,

    [Description("DISCOVER")]
    Discover,

    [Description("VISA")]
    Visa
}

public enum BillingFrequencyEnum
{
    [Description("Unknown")]
    Unknown,

    [Description("Annual")]
    Annual,

    [Description("Semi-annual")]
    SemiAnnual,

    [Description("Quarterly")]
    Quarterly,

    [Description("Bi-monthy")]
    BiMonthly,

    [Description("Ten months")]
    TenMonths,

    [Description("Monthly")]
    Monthly
}

public enum DirectDebitAccountTypeEnum
{
    [Description("Unknown")]
    Unknown,

    [Description("Checking Account")]
    Checking,

    [Description("Savings Account")]
    Savings
}

I'm not in love with having an enum to know what base type to cast to.  If you want to stick to it then I'll give you a couple of pointers then later I'll give you a couple more options to think about

Make the base abstract and make the enum abstract

public abstract class PaymentDetailBase
{
    protected PaymentDetailBase(string id)
    {
        this.Id = id;
    }

    public string Id { get; }

    public abstract PaymentMethodEnum PaymentMethod { get; }
}

if you are going to cast based on the Enum then you don't want it being sent in the constructor.  What if I sent in the wrong enum for the type

Now classes the inherit from the base will be forced to fill in the type

public class CardDetail : PaymentDetailBase
{
    public CardDetail(string id, string last4, DateTime expiry, PaymentCardTypeEnum cardType) : base(id)
    {
        this.Last4 = last4;
        this.Expiry = expiry;
        this.CardType = cardType;
    }

    public string Last4 { get; }

    public DateTime Expiry { get; }

    public PaymentCardTypeEnum CardType { get; }

    public override PaymentMethodEnum PaymentMethod => PaymentMethodEnum.CreditCard;
}

I've worked with applications like this and I don't really care for the Enum.  It violates the open/close principle.  If I want another payment type I need to change the enum and some switch code that does hardcoded cast (yuck).   And what are you saving?  A switch statement instead of getting the base class and doing the AS statement and checking for null?

Really when you run into this situation you need to think about your design.  What in the outside needs to know about those extended properties.  If everything then why cast to the base object in the first place just pass in the right class or you can try to make use of generics with constraints.

Another option is if not a lot needs to know about the specific class then have the class do the operation you want done.  For Example you need to just copy over those properties to an entity.  Then aleave the base class abstract and make an abstract method like

public void UpdateEntity(PaymentEntity entity);

now each class need to implement the update entity and it knows about it's own properties.


"Disease Spread" challenge Right now I'm solving this problem on codewars.com. I'm not sure about how to optimise the code further. Or is my algorithm inefficient? If it's an algorithmic issue, could someone help me how to go about it?

import java.util.Arrays;

class Epidem {

    public static int epidemic(int tm, int n, int s0, int i0, double b, double a) {
        // your code
     double dt = tm/n;
     double s1,i1,r,j;
     r=0;j=0;

     while(j<=tm)
      {
      s1 = s0 - dt*b*s0*i0;
      i1 = i0 + dt*(b*s0*i0 - a*i0);
      r = r + dt * i0 * a;
      s0 = (int) s1;
      i0 = (int) i1;
      j+=dt;
      }

     return (int) i0;

    }
}

It fails in the following cases:

int tm = 18 ;int n = 432 ;int s0 = 1004 ;int i0 = 1 ;double b = 0.00209 ;double a = 0.51;

    tm = 12 ;n = 288 ;s0 = 1007 ;i0 = 2 ;b = 0.00206 ;a = 0.45;

    tm = 13 ;n = 312 ;s0 = 999 ;i0 = 1 ;b = 0.00221 ;a = 0.55;

    tm = 24 ;n = 576 ;s0 = 1005 ;i0 = 1 ;b = 0.00216 ;a = 0.45;

    tm = 24 ;n = 576 ;s0 = 982 ;i0 = 1 ;b = 0.00214 ;a = 0.44;

    tm = 20 ;n = 480 ;s0 = 1000 ;i0 = 1 ;b = 0.00199 ;a = 0.53;

    tm = 28 ;n = 672 ;s0 = 980 ;i0 = 1 ;b = 0.00198 ;a = 0.44;

    tm = 14 ;n = 336 ;s0 = 996 ;i0 = 2 ;b = 0.00206 ;a = 0.41;

    tm = 13 ;n = 312 ;s0 = 993 ;i0 = 2 ;b = 0.0021 ;a = 0.51;

    tm = 28 ;n = 672 ;s0 = 999 ;i0 = 1 ;b = 0.00197 ;a = 0.55;

Already answered by @Thomasky:

double dt = ((double)tm) / n;

There are some common subexpressions, multiplications, you need to do only once. like b*(s0*i0) (integer multiplication first).

The while loop would better go as (more precise, faster):

for (int j = 0; j < n; ++j) {
    double bsi = dt*b*(s0*i0);
    double ai = dt*a*i0
    s0 -= (int) -bsi;
    i0 += (int) (bsi - ai);
    //r += ai; // As unused?
}

Variables can (and should) be declared as locally as possible, a declaration in a loop does not do more work as outside; there is just one slot reserved on the function stack.

The cast of (int) does no rounding.
As you might imagine, n*dt increases the approximation error in dt by n-fold. However more precision, a correction, would cost time.

Maybe using doubles, say double s1 = s0; double i1 = i0; instead of s0 and i0 would give a better solution. No idea.

And finally this task is solvable with a bit of math.


Improving models for a Django quiz I'm working on a little django quiz taking app. Currently I'm making it's models. So far I've got Quiz, Question, Answer, and Response designed as follows:

from django.db import models
from npage.mixins import TranslatedModelMixin
from django.contrib.auth.models import User

# Create your models here.

class Quiz(models.Model):

    title = models.CharField(max_length=60,blank=False,)

    # show_feedback = models.BooleanField(blank=False,default=True,help_text="Correct answer is shown after question.",)

    class Meta:
        verbose_name = "Quiz"
        verbose_name_plural = "Quizzes"

    def __unicode__(self):
        return self.title

class Question(models.Model, TranslatedModelMixin):

    quiz = models.ManyToManyField(Quiz, blank=True, )

    content = models.CharField(max_length=1000, blank=False, help_text="Enter the question text that you want displayed",verbose_name='Question',)
    es_content = models.CharField(max_length=1000, blank=True, help_text="Enter the question text that you want displayed",verbose_name='Question',)

    type = models.CharField(max_length=8, choices=TYPES, default='radio')
    is_scoreable = models.BooleanField(default=True, help_text="Will the answer to this question be scored?")

    # idea
    # tags = models.CharField(max_length=1000, blank=False, help_text="Enter some text to help you find this question to add it to quizzes later on.",verbose_name='Question',)

    feedback = models.TextField(max_length=2000,blank=True,help_text="Explanation to be shown after the question has been answered.",verbose_name='Explanation',)
    es_feedback = models.TextField(max_length=2000,blank=True,help_text="Explanation to be shown after the question has been answered.",verbose_name='Explanation',)

    TYPES = (
        ('radio', 'radio'),
        ('checkbox', 'checkbox'),
        ('text', 'text'),
    )

    language_code = 'en'
    translated_fields = ['content', 'feedback']

    class Meta:
        verbose_name = "Question"
        verbose_name_plural = "Questions"
        #ordering = ['category']

    def __unicode__(self):
        return self.content

class Answer(models.Model, TranslatedModelMixin):
    question = models.ForeignKey(Question)

    content = models.CharField(max_length=1000, blank=False, help_text="Enter the answer text that you want displayed",)
    es_content = models.CharField(max_length=1000, blank=False, help_text="Enter the answer text that you want displayed",)

    correct = models.BooleanField(blank=False, default=False,help_text="Is this a correct answer?")

    language_code = 'en'
    translated_fields = ['content']

    def __unicode__(self):
        return self.content

class Response(models.Model):
    user = models.ForeignKey(User)
    question = models.ForeignKey(Question)

    # Could have either an FK to an answer OR some free response text.
    answer = models.ForeignKey(Answer)
    free_response = models.TextField(max_length=2000,blank=True)

    def __unicode__(self):
        if self.answer:
            return self.answer
        else:
            return free_response

I am especially concerned with the elegance of my Response model. The idea here is a question might be multiple choice (radio group or checkbox group) OR free response (text) so a response could either be a foreign key to an answer (which may or may not be correct) OR just some plain text (probably not both). Is this a good design? What can I do to improve my models

You could have an abstract superclass Response which has concrete derived classes of multipleChoiceResponse and freeResponse. Then you can have a method such as checkResponse which is different for each type of respones.

EDIT:

How about this:

from django.db import models

class Response(models.Model):
    user = models.ForeignKey(User)
    question = models.ForeignKey(Question)

    class Meta:
        abstract = True

class freeResponse(Response):
    free_response = models.TextField(max_length=2000,blank=True)

class multipleChoiceResponse(Response) #does not handle multi-select (tickbox) cases
    answer = models.ForeignKey(Answer)


Code organization when using threads From OOP & OOD point of view, is it good idea to define Java-threads inside of the static method or in this case it's better to use instance-based method?

public class ThreadPool {

    public static void stringAnalysis(ArrayList<String> strData) {
        Thread t;
        t = new Thread(new SentimentAnalysis(strData));
        t.start();
    }
}

public class SentimentAnalysis implements Runnable {

    private ArrayList<String> strData;

    public SentimentAnalysis(ArrayList<String> strData) {
        this.strData = strData;
    }

    public void computeSentiment(ArrayList<String> strData) {
        StanfordNLP_forked.analyze(strData);
    }

    public void run() {
        this.computeSentiment(strData);
    }
}

StanfordNLP_forked is a forked version of StanfordCoreNLP for educational purpose only.  StanfordNLP_forked.analyze(strData) performs text analysis of the strings array and replace each string with sentimental rank value. For the moment, I just check in the debugger the result of the analysis, later I'll add some functionality.

The Best-practice threading policy in Java is now to use the ExecutorService implementations found in the java.util.concurrent package.
Before we go there, though, your current code should be improved. The method:

public static void stringAnalysis(ArrayList<String> strData) {
    Thread t;
    t = new Thread(new SentimentAnalysis(strData));
    t.start();
}

creates and starts a thread. The thread that is started is a regular thread, as opposed to a daemon thread. The JVM will exit when all threads complete, or all the remaining threads are Daemon (background) threads: see Thread.setDaemon(boolean).
You should typically use Daemon threads (and I believe that Java has a bug in that Daemon threads should be the default).
Additionally, there is no reason to 'Declare' the t Thread variable before assigning to it.
Finally, for many reasons, it is nice to give threads names.
I would have the code:
public static void stringAnalysis(ArrayList<String> strData) {
    Thread toRun = new Thread(new SentimentAnalysis(strData), "Sentiment Analysis thread");
    toRun.setDaemon(true);
    toRun.start();
}

But, in reality, I would use an Executor service....
Executors.
Executor services work best with Daemon threads too. Here's a method that creates a Daemon thread for an Executor service:
private static final AtomicInteger sentimentThreadID = new AtomicInteger();

public static Thread createSentimentThread(Runnable toRun) {
    String name = "Sentiment Thread " + sentimentThreadID.incrementAndGet();
    Thread myThread = new Thread(toRun, name);
    myThread.setDaemon(true);
    return myThread();
}

Executors have their own Runnable that they use to create the thread. When you have your runnable, you pass it to the Executor, and the Executor runs it on one of the Executor's threads.
So, you can create an ExecutorService with something like (using Java 8):
ExecutorService sentimentService = Executors.newCachedThreadPool(
        runnable -> createSentimentThread(runnable)
    );

Java 7 would be slightly longer with:
ThreadFactory factory = new ThreadFactory() {
   @Override
   public Thread newThread(Runnable r) {
     return createSentimentThread(r);
   }

};
ExecutorService sentimentService = Executors.newCachedThreadPool(factory);

Once you have the sentimentService, you can run your analysis Runnables with:
sentimentService.submit(new SentimentAnalysis(strData));


Simplify multiple jQuery click functions How can I simplify this jQuery code? I feel like I should be able to do this with one click function.

jQuery

$('.btn').eq(0).click(function () { $('.carousel').css({ 'left': '0%' }); });
$('.btn').eq(1).click(function () { $('.carousel').css({ 'left': '-100%' }); });
$('.btn').eq(2).click(function () { $('.carousel').css({ 'left': '-200%' }); });
$('.btn').eq(3).click(function () { $('.carousel').css({ 'left': '-300%' }); });

HTML

Button 1

Button 2

Button 3

Button 4

You are correct, you can have one function binding click events to all of your .btn elements.
Working Fiddle Example:
$('.btn').bind("click", function(event) {
  event.preventDefault();
  var index = $(this).parent().index();
  $('.carousel').css({ 'left': '-' + (index*100) + '%' });
});

jQuery documentation about index().
Describing what's being suggested:

Bind the click to the .btn class and within the click event you ascertain the index position:
I've opted to use bind() since it's performance efficient when compared with click().
Another reason is the fact that all your elements share the same class, so, you only need to bind a click event to the class instead of attaching a click handler to each .btn.

Use the index and multiply it by 100 as to get the desired left value:
This way you can easily ascertain the correct value since you have a direct relation between the anchor's parent index and the desired left value.

Using event.preventDefault(); to prevent the browser from following the href:
With this, you tell the browser to leave the href attribute alone, thus preventing it to bubble up.

Safe to use the minus signal all the time, since 0 and -0 is the same thing.

In order to further improve the function, and if using the lastest jQuery, I would give an id to the ul element, thus losing the .btn class, having the click event binded to a single DOM element thru delegation:
$('#myUL').on("click", "a", function(event) {
  event.preventDefault();
  var index = $(this).parent().index();
  $('.carousel').css({ 'left': '-' + (index*100) + '%' });
});

jQuery documentation about on().
Useful reading: Why use jQuery on() instead of click().


Python lazy dict with iterator in constructor This question began as an off-topic answer to this question, but the code here serves a different goal.

I wrote the following class for the purpose of populating a dict on demand from an iterator. The intent of the iterator passed to the constructor is that it could alternatively be passed to dict, which would consume the entire iterator in its constructor; an instance of this class consumes the iterator just far enough to locate a requested item. Such an iterator would be similar in spirit to a return value from dict.items.

class LazyDict(dict):
    """ A dict built on demand from an iterator """

    def __init__(self, iterator):
        super().__init__()
        self.iterator = iterator

    def __getitem__(self, item):
        while not self.get(item):
            try:
                (key, value) = next(self.iterator)
                self[key] = value
            except StopIteration:
                raise AttributeError
        return super().__getitem__(item)

    def __contains__(self, item):
        try:
            self[item] # pylint: disable=pointless-statement
            return True
        except AttributeError:
            return False

Here is my calling code (with other details of the Directory code omitted; if more of that is needed in this context I can provide it):

class Directory(object):
    @Lazy
    def hash(self):
        """ Lazy dict mapping entry names to entries """
        return LazyDict((self.name(entry), entry) for entry in self.readdir())

    def __contains__(self, name):
        return name in self.hash # pylint: disable=unsupported-membership-test

    def __getitem__(self, name):
        return self.hash[name] # pylint: disable=unsubscriptable-object

The code for Lazy is equivalent to lazy_property in this answer.

As I write this, it occurs to me that perhaps Directory should itself be a subclass of LazyDict rather than containing a LazyDict (that might be a better way to stifle those pylint warnings). Whether that seems right might be one specific question to fall out of this. Upon further investigation, here is an alternate version of the calling code:

class Directory(LazyDict):
    def __init__(self, mem, size):
        super().__init__((self.name(entry), entry) for entry in self.readdir())
        self.mem = mem
        self.size = size

As before, some details of Directory are omitted (the implementations of name and readdir are not included for either version), but this version of the code inherits __getitem__ and __contains__ from LazyDict rather than overriding them. The most visible difference between the two versions of the calling code is due to Directory inheriting __repr__ from dict rather than object.

Another specific question might be the role of keys and values and items in LazyDict. The methods inherited from dict reveal how much of the iterator has been consumed; convincing them to reveal all items is one AttributeError away (I can attempt to fetch self[None] within Directory to fully populate the cache). My inclination is to limit on-demand operations to __getitem__ and __contains__, but opinions on that point are welcome.

Suggestions for other ways to approach this are also welcome.

1. Design

I think that it's a mistake to inherit from dict. My reasoning is as follows:

LazyDict is effectively read-only: that is, setting an item does not update the underlying iterator. (In the described use case, you can't update the compressed file image through this dictionary.) So it is misleading to offer (as you do) a __setitem__ method (and similarly for update, pop, setdefault and other mutating methods).
Programmers are used to the equivalence of dictionary methods: for example, they "know" that d.get(k) behaves just the same as d[k] if k in d else None. But in your implementation it does not — calling d.get(k) does not consult the iterator but calling k in d or d[k] does. This seems like a recipe for confusion and bugs.

So I think the better approach is not to inherit from dict, but to have a dictionary as an attribute. This means that users will only be able to call the methods that you choose to implement, instead of accidentally calling through to methods on the underlying dict. This approach also makes the code clearer, because you can distinguish key in self from key in self._dict without needing to use super() or have pylint annnotations.

2. Other review comments

The parameter to the __getitem__ and __contains__ methods would be better named key.
The exception raised from a failed key lookup should be KeyError, not AttributeError, for consistency with dict.
The exception raised on a failed key lookup should include the failed key, for consistency with dict and to help programmers track down errors.
It's a good idea to keep try: ... except: ... blocks as small as possible, so that you don't accidentally capture exceptions that you weren't expecting. In this case you are expecting a StopIteration from the call to next so that's the only line that needs to be protected.
It's conventional to give attributes that are not intended to be used outside of the class (like iterator) the prefix _.

3. Revised code

class LazyDict:
    """A dictionary built on demand from an iterator."""
    def __init__(self, iterator):
        self._dict = {}
        self._iterator = iterator

    def __getitem__(self, key):
        if key in self:
            return self._dict[key]
        else:
            raise KeyError(key)

    def __contains__(self, key):
        while key not in self._dict:
            try:
                k, v = next(self._iterator)
            except StopIteration:
                return False
            self._dict[k] = v
        return True

Now someone who tries to call the get method will get an exception instead of silently getting the wrong result.


Function to call a list of callables with retry This script is designed to be run via windows task scheduler once per day.

All callables passed to this function should only return a bool. The callables are called until either the maximum number of call attempts is reached, or until they return True. If one or more callables returns False, the program will sleep for the alloted time 'attempt_interval', before attempting to calls again to those which have not yet returned True.

Function:

import time
from dateutil.parser import parse

def call_callables(callables: list,
                   max_attempts=12,
                   earliest_attempt="07:00",
                   attempt_interval=600):
    """
    Call each callable until it either returns True or max_attempts is reached

    :param callables: a list of callable functions/methods which return
                      either True or False.
    :param earliest_attempt: For the current day, don't attempt list generation
                             before this time. This is a target time for the
                             first attempt.
    :param max_attempts: The maximum number of calls to each callable
    :param attempt_interval: The number of seconds to wait between calls to each
                             callable
    """

    earliest_attempt = parse(earliest_attempt)
    current_time = datetime.datetime.now()

    # track number of attempts for each callable
    attempt_counter = defaultdict(int)

    # track return bool status for each callable
    success_tracker = defaultdict(bool)

    callable_objs = callables

    while callable_objs:
        for callable_obj in callables:
            success_tracker[callable_obj] = callable_obj()
            attempt_counter[callable_obj] += 1

            if (success_tracker[callable_obj] or attempt_counter[callable_obj]
                >= max_attempts):
                callable_objs.remove(callable_obj)
                continue

        # Unsuccessful (False returned by one or more callables) attempt. Retry.
        if callable_objs:
            time.sleep(attempt_interval)

    # return dicts to allow for testing
    return attempt_counter, success_tracker

Test (using pytest-cov; this passed):

import pytest
from unittest.mock import Mock, patch

@patch("time.sleep")
def test_call_callables(sleep):
    mock_true = Mock()
    mock_false = Mock()

    def ret_true():
        return True

    def ret_false():
        return False

    mock_true.call_method = ret_true
    mock_false.call_method = ret_false

    mocks = [mock_true.call_method, mock_false.call_method]

    attempt_tracker, success_tracker = call_callables(callables=mocks,
                                                      max_attempts=10,
                                                      attempt_interval=1)
    assert {ret_true: 1, ret_false: 10} == dict(attempt_tracker)
    assert sleep.call_count == 10
    assert {ret_true: True, ret_false: False}  == dict(success_tracker)

You are not allowed to remove items from a list while iterating over the list.

>>> a = [“a”, ”b”, ”c”, ”d”]
>>> for b in a:
...   print(a,b)
...   a.remove(b)
...
['a', 'b', 'c', 'd'] a
['b', 'c', 'd'] c
>>>

You should wait to remove the callable_obj from callable_objs until after the for loop completes.  Build a list of callable_obj to remove, and bulk remove them at the end.  Or use list comprehension and filter out the successful calls:

callable_objs = [ obj for obj in callable_objs if not success_tracker[obj] ]


Solving "Quadruple sum" problem using dynamic programming I am trying to learn dynamic programming using hash table. I was given this the "Quadruple sum" problem from firecode.io as a challenge:

  Given a sorted array of integers and an integer target, find all the unique quadruplets which sum up to the given target.

  Note: Each quadruplet must have elements (input[i], input[j], input[k], input[l]), such that \$i < j < k < l\$. The ordering of unique quadruplets within the output list does not matter.

  Examples:

Input : [1,2,3,4,5,6,7,8]
Target: 10
Output: [(1, 2, 3, 4])]

Input : [1,2,3,4,5,6,7]
Target: 20
Output: [(2, 5, 6, 7), (3, 4, 6, 7)]

solution #1

def all_sums(xs):
    dict = {}
    l = [[(i,j) for i in range(len(xs)) if i < j] for j in range(len(xs))]
    pairs = [item for sublist in l for item in sublist]
    for i,j in pairs:
        if xs[i]+xs[j] not in dict:
            dict[xs[i]+xs[j]] = set()
        dict[xs[i]+xs[j]].add((i,j))
    return dict

def iquadruple_sum(xs, target):
    sums = all_sums(xs)
    for s, positions in sums.items():
        for (k,l) in positions:
            if target - s in sums:
                for (i,j) in sums[target - s]:
                    if len({i,j,k,l}) == 4: yield sorted((xs[i],xs[j],xs[k],xs[l]))

def quadruple_sum(xs, target):
    return list(set(tuple(x) for x in iquadruple_sum(xs, target)))

\$O(n^4)\$ in the worst case (if the array is mostly complementary). It also takes \$O(n^2)\$ space, vs \$O(n)\$. The worst case is unlikely though.

Alternative solution #2

#
def all_sums(xs):
    "Returns dictionary of all possible ordered sums in O(n^2) time and space."
    from collections import defaultdict
    from itertools import product
    d = defaultdict(set)
    pairs = ((i,j) for (i,x),(j,y) in product(enumerate(xs), enumerate(xs)) if i<j)
    for i,j in pairs: d[xs[i]+xs[j]].add((i,j))
    return d

def iquadruple_sum(xs, target):
    sums = all_sums(xs)
    for s, positions in sums.items():
        for (k,l) in positions:
            for (i,j) in sums[target - s]:
                if len({i,j,k,l}) == 4: yield sorted((xs[i],xs[j],xs[k],xs[l]))

def quadruple_sum(xs, target):
    return list(set(tuple(x) for x in iquadruple_sum(xs, target)))

Just reviewing solution 2.

1. Bugs

Some inputs cause the code to raise an exception:

>>> quadruple_sum([1, 2, 3, 4, 5], 10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "cr185635.py", line 21, in quadruple_sum
    return list(set(tuple(x) for x in iquadruple_sum(xs, target)))
  File "cr185635.py", line 21, in <genexpr>
    return list(set(tuple(x) for x in iquadruple_sum(xs, target)))
  File "cr185635.py", line 14, in iquadruple_sum
    for s, positions in sums.items():
RuntimeError: dictionary changed size during iteration

The problem is with the line:

for (i,j) in sums[target - s]:

sums is a collections.defaultdict, and this means that if target - s is not already in the dictionary, then merely looking up the value causes the dictionary to be updated. There needs to be a guard like the one you have in solution 1:

if target - s in sums:
    for i, j in sums[target - s]:

(In practice you'd want to move the guard outside the loop over k, l as well.)
The code constructs the quadruple like this:

yield sorted((xs[i],xs[j],xs[k],xs[l]))

This means that the quadruple is sorted in order by its elements, but in the problem description it says, "Each quadruplet must have elements (input[i], input[j], input[k], input[l]), such that \$i<j<k<l\$", in other words, the quadruples must be sorted in order by their indices.

>>> quadruple_sum([4, 3, 2, 1], 10)
[(1, 2, 3, 4)] # expected [(4, 3, 2, 1)]

This also causes some quadruples to be missed:

>>> quadruple_sum([2, 1, 1, 2, 2], 6)
[(1, 1, 2, 2)] # expected [(1, 1, 2, 2), (2, 1, 1, 2)]

This problem is easy to miss if you only ever test with the input in sorted order. The correct code needs to look something like this:

yield tuple(xs[m] for m in sorted((i, j, k, l)))

2. Testing

How could you have found these bugs? By testing, of course! It's easy to spot that the problem can be solved like this:

list(set(q for q in combinations(xs, 4) if sum(q) == target))

This is inefficient (takes \$Θ(n^4)\$ in all cases) but is clearly correct, so we can use it as a test oracle together with randomized test case generation. For example,

import random
import unittest

class TestQuadupleSum(unittest.TestCase):
    def test_quadruple_sum(self):
        for _ in range(100):
            n = random.randrange(10)
            xs = [random.randrange(10) for _ in range(n)]
            if len(xs) >= 4 and random.random() < .9:
                target = sum(random.sample(xs, 4))
            else:
                target = random.randrange(sum(xs) + 1)
            expected = list(set(q for q in combinations(xs, 4)
                                if sum(q) == target))
            found = quadruple_sum(xs, target)
            self.assertCountEqual(expected, found,
                                  "xs={}, target={}: expected {} but found {}"
                                  .format(xs, target, expected, found))

This soon fails with one of the bugs in §1 above:

======================================================================
FAIL: test_quadruple_sum (cr185635.TestQuadupleSum)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "cr185635.py", line 59, in test_quadruple_sum
    .format(xs, target, expected, found))
AssertionError: Element counts were not equal:
First has 1, Second has 0:  (1, 5, 8, 3)
First has 0, Second has 1:  (1, 3, 5, 8) :
xs=[1, 5, 8, 7, 3], target=17: expected [(1, 5, 8, 3)] but found [(1, 3, 5, 8)]
----------------------------------------------------------------------

3. Review

The term "dynamic programming" is normally used to describe the technique in which you build up the solution for a large problem instance by combining the solutions for smaller instances of the same problem. For example, in the well-known "change-making problem" you have to count the number of ways of making change for an amount \$a\$, and in the dynamic programming approach you count the number of ways of making change for various amounts \$b < a\$ and then add them. (The name "dynamic programming" is a bit obscure and I wrote a piece about this on my blog.)

What you have here is not "dynamic programming" in the usual sense of the term, since the code does not work by finding solutions to smaller instances of the "quadruple sums" problem and then combining them.
Solution 2 makes a list of pairs of distinct indexes like this:

pairs = ((i,j) for (i,x),(j,y) in product(enumerate(xs), enumerate(xs)) if i<j)

When you want to generate distinct subsets of a collection without repetition, you need itertools.combinations. In this case you would write:

pairs = ((i,j) for (i,x),(j,y) in combinations(enumerate(xs), 2))

The code then looks up the elements at these pairs of indices, like this:

for i,j in pairs: d[xs[i]+xs[j]].add((i,j))

But in fact xs[i] and xs[j] were the values x and y that you got out of the enumeration on the previous line but then discarded! Instead of discarding these elements and then looking them up again, hang on to them and use them:

for (i, x), (j, y) in combinations(enumerate(xs), 2):
    d[x + y].add((i, j))

The value of target - s does not change in any of the inner loops, so you could cache it in a local variable and avoid recomputing it.
The two loops over positions and target - s:

for (k,l) in positions:
    for (i,j) in sums[target - s]:

can be combined into one using itertools.product:

for (i, j), (k, l) in product(positions, sums[target - s]):

The functions all_sums and iquadruple_sum are short and each is called from just one place, so it might make sense to inline them at their single point of use.

4. Revised code

def quadruple_sum(xs, target):
    "Return list of unique quadruples of xs that add up to target."
    # Map from sum to set of pairs of indexes with that sum.
    sums = defaultdict(set)
    for (i, x), (j, y) in combinations(enumerate(xs), 2):
        sums[x + y].add((i, j))
    result = set()
    for s, pairs in sums.items():
        t = target - s
        if t in sums:
            for (i, j), (k, l) in product(pairs, sums[t]):
                indexes = {i, j, k, l}
                if len(indexes) == 4:
                    result.add(tuple(xs[m] for m in sorted(indexes)))
    return list(result)


Google Guice module that loads two kinds of views The code of my Guice Module looks like this:

public class FXMLModule extends AbstractModule {

    private final Locale locale = Locale.getDefault();
    private final ResourceBundle messages = ResourceBundle.getBundle("i18n.messages", locale);

    @Override
    protected void configure() {
        bind(Controller.class).annotatedWith(MainView.class).to(MainController.class);
        bind(Controller.class).annotatedWith(MovieView.class).to(MovieViewController.class);
    }

    @Provides @MainView
    public FXMLLoader mainViewLoader(@MainView Controller controller) {
        FXMLLoader loader = new FXMLLoader(locate("/jfx/fxml/MainView.fxml"), messages);
        loader.setController(controller);
        return loader;
    }

    @Provides @MovieView
    public FXMLLoader movieViewLoader(@MovieView Controller controller) {
        FXMLLoader loader = new FXMLLoader(locate("/jfx/fxml/MovieView.fxml"), messages);
        loader.setController(controller);
        return loader;
    }

    private URL locate(String location) {
        return getClass().getResource(location);
    }

}

Basically I want to inject fully configured FXMLLoaders into some Controller classes, so that they can work with the root nodes returned from the loaders without having to know anything about other controllers. The MainViewLoader gets injected into the Application class, and the MovieViewLoader gets injected into MainViewController. It works, but I'd have to write a provide method (with almost the same code) for every loader/controller. Any ideas how to make this more generic?

What this is looking for is "Binding by Convention". Since Guice is intended to be as lightweight (and fast) as possible, it does not contain facilities to enable binding by convention.
Neither does Spring for that matter. I think you might be able to automate the bindings injected into the methods if you use Plexus.
Do note that none of this will alleviate you from the actual problem you're facing:
Why?
You write:

Basically I want to inject fully configured FXMLLoaders into some
Controller classes, so that they can work with the root nodes returned
from the loaders without having to know anything about other
controllers.

This makes  no sense: You're injecting FXMLLoaders into Controllers, specifically into a controller that's not the Controller you set on the FXMLLoader itself. To access the rootNode returned by the loader.
This violates the Law of Demeter. You're grabbing into the responsibilities of another controller.
The solution to this problem is to expose a method on the controller and inject a the controller instance you need, instead of the loader.
This whole module seems to me like it's solving the wrong problem in the first place ...


Conway's Game of Life command line program in C++ I have programmed Conway's Game of Life in C++.

/*
    Any live cell with fewer than two live neighbors dies, as if by under population.
    Any live cell with two or three live neighbors lives on to the next generation.
    Any live cell with more than three live neighbors dies, as if by overpopulation.
    Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
*/

#include <iostream>
#include <fstream>
#include <array>
#include <vector>
#include <string>
#include <stdlib.h>

#define EXTRA_SPACE 1
#define GRID_SIZE 35

#define ALIVE_CELL '#'
#define DEAD_CELL ' '

struct CellCoords { int y, x; };

void setup_grid();
void generation();
void display_grid();
void sleep(int);

std::array<std::array<char, GRID_SIZE + EXTRA_SPACE * 2>, GRID_SIZE + EXTRA_SPACE * 2> grid;

int main() {

    setup_grid();

    int gen = 1;

    do {
        system("cls");
        std::cout << std::endl << "Generation " << gen << std::endl;
        display_grid();
        sleep(100);
        generation();
        gen++;
    } while (true);

    std::cin.get();
    return 0;
}

void setup_grid() {

    std::ifstream file("grid.txt");
    std::string line;
    int i = EXTRA_SPACE;

    while (std::getline(file, line)) {
        for (int j = EXTRA_SPACE; j < GRID_SIZE; j++) {
            if (line[j] == '1')
                grid[i][j] = ALIVE_CELL;
            else
                grid[i][j] = DEAD_CELL;
        }
        i++;
    }

    file.close();
}

void generation() {

    std::vector<CellCoords> cells_to_kill;
    std::vector<CellCoords> cells_to_be_born;

    int neighbors;

    for (int y = EXTRA_SPACE; y < GRID_SIZE; y++) {
        for (int x = EXTRA_SPACE; x < GRID_SIZE; x++) {

            neighbors = 0;

            if (grid[y - 1][x    ] == ALIVE_CELL) neighbors++;
            if (grid[y - 1][x + 1] == ALIVE_CELL) neighbors++;
            if (grid[y    ][x + 1] == ALIVE_CELL) neighbors++;
            if (grid[y + 1][x + 1] == ALIVE_CELL) neighbors++;
            if (grid[y + 1][x    ] == ALIVE_CELL) neighbors++;
            if (grid[y + 1][x - 1] == ALIVE_CELL) neighbors++;
            if (grid[y    ][x - 1] == ALIVE_CELL) neighbors++;
            if (grid[y - 1][x - 1] == ALIVE_CELL) neighbors++;

            if (grid[y][x] == ALIVE_CELL) {
                if (neighbors < 2 || neighbors > 3)
                    cells_to_kill.push_back({ y, x });
            } else if (neighbors == 3) {
                    cells_to_be_born.push_back({ y, x });
            }
        }
    }

    for (int i = 0; i < cells_to_kill.size(); i++) {
        CellCoords cell = cells_to_kill[i];
        grid[cell.y][cell.x] = DEAD_CELL;
    }

    for (int i = 0; i < cells_to_be_born.size(); i++) {
        CellCoords cell = cells_to_be_born[i];
        grid[cell.y][cell.x] = ALIVE_CELL;
    }
}

void display_grid() {

    std::cout << std::endl;

    for (int y = EXTRA_SPACE; y < GRID_SIZE; y++) {
        for (int x = EXTRA_SPACE; x < GRID_SIZE; x++) {
            std::cout << grid[y][x] << ' ';
        }
        std::cout << std::endl;
    }
    std::cout << std::endl;
}

void sleep(int time) {
    for (int i = 0; i < time; i++);
}

How can I improve the code? Was making an extra 2 rows and columns in the grid array a good idea?

Overall, this is pretty good. You've avoided the most common mistakes I see, like bad naming, using magic numbers, passing bare values that really belong together in a data structure. Nice job! I appreciate the comment at the top that explains the rules, too.
To answer your question, I think that using the extra rows and columns is a great idea. They're 2 characters per row, and 2 extra rows. It's not a lot of memory, and it makes the code much cleaner.
Here are some thoughts on some things that could be improved.
Avoid Globals
Your game board is a global variable. You've structured the code nicely, so it only ever gets modified in generation(), but small programs have a tendency to become large programs, and global variables in large programs have a tendency to get modified all over the place. I'd move the grid variable into main() and pass a reference to it into the various functions that use it.
Always Name Your Arguments
Your definition of the sleep() function looks like this:
void sleep(int);

What is the int? A function prototype with unnamed arguments is close to useless. Now I have to read through the function to get any useful information about what the parameter means. If it was named something like iterations or time like in the actual function it would be infinitely better.
Things in main()
The gen variable is set up, and it's incremented, but it's never checked. It's just busywork for your CPU. If you were going to use it to bail out of the loop after so many iterations, it would be useful, but you've made an infinite loop. So I'd just get rid of it.
You're using std::endl at the end of every line you print. That's pretty heavy-weight. It flushes the output buffer. I'd say in most cases you want to just use "\n" instead. Maybe you could use std::endl after printing the last character of the board.
Your command to clear the screen is non-standard. My system doesn't have a command named cls on it, so that just outputs an ugly error message. I don't do a lot of console programming, so I'm not sure if there's a universal way to clear the screen, but you might look into ANSI escape codes.
The sleep() Function
Likewise, your sleep() function has some issues. There's a standard POSIX function named sleep() that is often used to sleep the process for an amount of time. I don't know whether it exists on Windows or not. But regardless of that, the way you've implemented it, it will sleep for a different amount of time on different machines. So a 1GHz machine will probably take twice as long to complete that loop as a 2GHz machine. You probably don't want that. I recommend finding a more standard method for performing sleep on your target system. Something that at least checks the clock rather than just counting.
According to the comments, you can use:
#include <chrono>
#include <thread>
...
std::this_thread::sleep_for(std::chrono::milliseconds(500));

setup_grid()
For the most part, setup_grid() looks pretty decent. If any errors occur, you will end up with a partially uninitialized grid, though. You might want to at least clear it all to DEAD_CELL to start with so you have something sensible in there. Better yet, if any errors occur, return them to the caller and let the caller decide how to handle them (tell the user, exit the program, whatever).
You don't need the file.close() at the end. The destructor for std::ifstream will call it for you when the function ends.
generation()
This function is pretty well written, too. I didn't have time to do timing trials, but I have to wonder if using the same grid for input and output is fastest? (Not that it matters given your sleep() function!) Another way to handle it would be to pass in 2 grids - the current state and the next state. Rather than noting which cells changed and then overwriting them, you'd simply fill in the new cells given the state of the old cells. It might be a wash, though. You could code it up and profile it to be sure.
There's nothing wrong with the set of if statements you have for checking the cells. In fact, some would argue that you've done loop unrolling which could theoretically improve performance. I think it would be easier to read, though, if it were done in a loop like this:
for (int cell_y = y - 1; cell_y < y + 1; ++cell_y) {
    for (int cell_x = x - 1; cell_x < x + 1; ++cell_x) {
        if (grid[cell_y][cell_x] == ALIVE_CELL) {
            neighbors++;
        }
    }
}

As noted, this will count the current cell, so you can subtract it out at the end with:
if (grid[y][x] == ALIVE_CELL) {
    neighbors--;
}

At the very least, you should avoid writing the condition and the statement it executes on the same line, as it makes it impossible to tell whether the statement executed or not when stepping through with a debugger. Not a big deal here, but it can be in larger programs, so it's a good habit to avoid putting it all on one line.
I recommend always using braces in if statements, even if they're only one line as that avoids another common error, which is adding a line to an if without realizing you didn't actually add it. Like this:
 if (someCondition)
    doSomething();
    doSomethingElse();

In this case, doSomethingElse(); will be called regardless of whether someCondition is true or false because there are no braces around the intended body of the if statement.


MongoDB CRUD operations for various types of data in Go First of all I am a newbie in Go. I wrote a CRUD REST API that consists of handlers, a database layer and so on, and it contains a lot of code duplication. I see some patterns here, and I know how to reuse code in some other languages like JS or Java using generics or dynamic types.

What are my options in Go? Note that I don't want to use interface{}.

Here is my userdb CRUD set of function that create, update and so on.

package userdb

import (
    "github.com/atsman/interviewr-go/models"
    "github.com/op/go-logging"
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

var log = logging.MustGetLogger("db.user")

func GetUserC(db *mgo.Database) *mgo.Collection {
    return db.C(models.CollectionUsers)
}

func Create(db *mgo.Database, user *models.User) error {
    return GetUserC(db).Insert(user)
}

func Update(db *mgo.Database, id *bson.ObjectId, user *map[string]interface{}) (error, *models.User) {
    var updatedUser = models.User{}
    err := GetUserC(db).UpdateId(id, bson.M{
        "$set": user,
    })
    if err != nil {
        return err, &updatedUser
    }

    err = GetUserC(db).FindId(id).One(&updatedUser)
    return err, &updatedUser
}

func List(db *mgo.Database, query *bson.M) (error, *[]models.User) {
    var users []models.User
    err := GetUserC(db).Find(bson.M{}).All(&users)
    return err, &users
}

func Delete(db *mgo.Database, id *bson.ObjectId) (error, *models.User) {
    var user = models.User{}
    err := GetUserC(db).FindId(id).One(&user)
    if err != nil {
        return err, &user
    }

    err = GetUserC(db).RemoveId(id)
    if err != nil {
        return err, &user
    }

    return nil, &user
}

And here is my companydb package. Its goals are almost the same except with the Company model.

package companydb

import (
    "github.com/atsman/interviewr-go/models"
    "github.com/op/go-logging"
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

var log = logging.MustGetLogger("db.company")

func GetCompanyC(db *mgo.Database) *mgo.Collection {
    return db.C(models.CollectionCompanies)
}

func Create(db *mgo.Database, company *models.Company) error {
    return GetCompanyC(db).Insert(company)
}

func Update(db *mgo.Database, id *bson.ObjectId, user *map[string]interface{}) (error, *models.Company) {
    updatedCompany := models.Company{}
    err := GetCompanyC(db).UpdateId(id, bson.M{
        "$set": updatedCompany,
    })
    if err != nil {
        return err, &updatedCompany
    }
    err = GetCompanyC(db).FindId(id).One(&updatedCompany)
    return err, &updatedCompany
}

func List(db *mgo.Database, query *bson.M) (error, *[]models.Company) {
    var companies []models.Company
    err := GetCompanyC(db).Find(bson.M{}).All(&companies)
    return err, &companies
}

func Delete(db *mgo.Database, id *bson.ObjectId) (error, *models.Company) {
    company := models.Company{}
    err := GetCompanyC(db).FindId(id).One(&company)
    if err != nil {
        return err, &company
    }

    err = GetCompanyC(db).RemoveId(id)
    if err != nil {
        return err, &company
    }

    return nil, &company
}

The same duplication exists in my handlers. There is a lot of stuff like get struct from JSON, check for errors and so on. I am thinking of some generic stuff.

So, I think the question is quite easy for guys with some experience. How can I generalize this? Or I shouldn't care at all, maybe it is not a big deal here?

I am also starting out in go (although I used GAE's Datastore), and have spent some time thinking about this. I considered 3 options:
1 Code Generation
I think code generation would be a solid way to approach this solution. There's even a library starting out called streetCURD for PostgreSQL.
Code generation seems like a common way to do things in go. There is also a golang code generation tool called gen.
2 Don't Generalize
Depending on how many times you will copy and paste this, it may not be worth for you to generalize it. However, I find that after a few structs I start doubting this route... and others are not generalizing too: Example1. example2.
3 Interfaces
I ended up using interface{} for somethings (like error checking) which you stated you are not interested in. I felt it made the code more readable, which is my goal.
Looking over your code, it seems like you are interested in a method that return a user or a company- depending in the input, interface{} would be the way to go... (pun not intended).
Since I am just starting out, I'd love to see better responses to this question.


First ever unit test. Am I headed in the right direction? I'm learning backbone.js in parallel with unit testing.  I've just made a simple model and wanted to unit test it.  Do I have the right idea? I am simply making a model with some default values.

Person = Backbone.Model.extend({
defaults: {
    name: "fetus",
    age: 0,
    child: ''
},

initialize: function() {
    console.log("Welcome to this world");
}
});

var test_Person = {};

var test_Person.Defaults = function() {
    var person = new Person();

    person.assertString(person.defaults.initialize,"Welcome to this world");
    person.assertString(person.defaults.name,"fetus");
    person.assertNum(person.defaults.age,0);
    person.assertString(person.defaults.child,"");
}();

If your Person was initialized with a name other than "fetus", your test would fail.. but your test has several reasons for failing and that's what makes it not-so-good: that same test would also fail if a Person was "born" with a child (!) or if age defaulted to 1, or if the welcome to this world string was different.

I've never written a unit test with JS, but I believe the following would apply:

Name your test method so that anybody (including non-technical) reading it (the name) knows exactly what is being tested.
Arrange the dependencies of your SUT (that's System Under Test). Set up /configure your mocks, define what the expected outcome should be.
Act upon your SUT (i.e. call the method you want to test). Pass in your mock dependencies, retrieve the "actual" result.
Assert - verify that you get expected results, i.e. make the test pass, or fail.

In this particular case, I'm not sure what's being tested exactly - you're merely verifying that the person object was initialized with the expected default values? I guess it's ok.

Unit tests should be testing that the code does what it's supposed to be doing.

As I said I've never written a test with JS, so this example is C#:

    [TestMethod]
    public void ShouldReplaceCommaWithEmptyStringInProductDescription()
    {
        // arrange
        var testDescription = "Product,Description";
        var data = GetValidMockRecord();
        var values = data.Split(',');
        values[11] = testDescription;
        data = string.Join(",", values);

        if (!testDescription.Contains(",")) Assert.Inconclusive("testDescription must contain at least one (1) comma (,).");

        var sut = new EdiParser();
        var expected = testDescription.Replace(",", string.Empty);

        // act
        var result = sut.Parse(data);
        var actual = result.ProductDescription;

        // assert
        Assert.AreEqual(expected, actual);
    }

I don't think the language is a barrier: as you can see I'm asserting in my arrange section and making the test inconclusive if the test data would make the test, well, inconclusive. Then in the actual assert section I'm only testing one thing, and this is what unit testing is really about.


LRU cache design using dict and doubly linked list Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

  get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
  set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

This problem can be easily solved by using collections.OrderedDict. But I'd like to do the practice by using dict and doubly linked list. Can anyone help me check the following code?

class LRUCache:
    # dictionary + doubly linked list
    class Node:
        def __init__(self, key, value):
            self.prev = None
            self.key = key
            self.value = value
            self.next = None

    # @param capacity, an integer
    def __init__(self, capacity):
        self.capacity, self.dict = capacity, {}
        self.head, self.tail = self.Node('head', 'head'), self.Node('tail', 'tail') # dummy head node and dummy tail node
        self.head.next = self.tail
        self.tail.prev = self.head

    # @return an integer
    def get(self, key):
        if key not in self.dict:
            return -1
        else:
            self.insertNodeAtFirst(self.unlinkNode(self.dict[key]))
            return self.dict[key].value

    # @param key, an integer
    # @param value, an integer
    # @return nothing
    def set(self, key, value):
        if key in self.dict:
            self.insertNodeAtFirst(self.unlinkNode(self.dict[key]))
            self.dict[key].value = value
        else:
            if len(self.dict) >= self.capacity: # remove the least recently used element
                del self.dict[self.unlinkNode(self.tail.prev).key]
            self.dict[key] = self.Node(key, value)
            self.insertNodeAtFirst(self.dict[key])

    def unlinkNode(self, node):
        node.prev.next = node.next
        node.next.prev = node.prev
        node.prev = None
        node.next = None
        return node

    def insertNodeAtFirst(self, node):
        node.prev = self.head
        node.next = self.head.next
        self.head.next.prev = node
        self.head.next = node

First off, the way you're commenting your functions is completely wrong. Proper commenting for functions uses Python docstrings. For example:

def my_func( ... ):
    """
    Write a description of your
    function and it's arguments
    here.
    """
    ...

Secondly, according to Python's official style guide, PEP8, your naming is incorrect. Variables and functions should be in snake_case, and classes should be in PascalCase. If the variable is a constant, it should be in UPPERCASE_SNAKE_CASE.

Finally, why do you have Node as a subclass of LRUCache? Why can't Node be a top-level class? I see no reason it shouldn't be.


Finding the count of all repeats in an array of integers The problem is about finding the sum of all repeating groups from an integer array as explained below and here.

Problem statement:

  Say that a "clump" in an array is a series of 2 or more adjacent
  elements of the same value. Return the number of clumps in the given
  array.

countClumps({1, 2, 2, 3, 4, 4}) → 2
countClumps({1, 1, 2, 1, 1}) → 2
countClumps({1, 1, 1, 1, 1}) → 1

  Conditions for solving:

  No other helper methods.
  Do not use Java.util.Arrays.copyOf or any other utility under Arrays
  Do not use collections.

Can I solve it using 1 loop with or with a better time complexity?

Any other nitpicks about my solutions are also welcome.

public int countClumps(int[] nums) {
    final int len=nums.length;
    int  count=0;

    for(int i=0;i<len;i++)
    {
        int j=i+1;
        if(nums[i]==nums[j])
        {
            count++;
            while((nums[i]==nums[j]))
            {
                if(j==len-1)
                    break;
                j++;
            }
        }
        i=j-1;
        if(i==len-2)
            break;
    }

    return count;
}

Your code has a for-loop with a nested while-loop. Typically this would indicate an \$O(n^2)\$ time complexity for your solution.... but, your code is only actually \$O(n)\$... how does that happen?

Because you do for-loop control variable manipulation outside the for-loop control block. This is a bad practice. A for loop has three control statements: for (initializer, terminator, stepper). A for loop is designed to have those three mechanisms in one place. In your code, you have split the logic of the stepper in to two places, which makes the for-loop hard to read, and unconventional. Your i variable is stepped, and also you have i=j-1; later in your loop.

If you cannot implement a clean for-loop structure because your code demands some other mechanism, then you should instead use a while-loop, or find a different way to express your step-process.

Bhushan has provided an answer which solves the problem, but does not implement a clean break-processing loop. His code implements the logic check when leaving a clump, rather than when entering the clump. If you do the check when the clump starts, the logic becomes much simpler:

public int countClumps(int[] nums) {
  boolean inclump = false;
  int clumpcnt = 0;
  // note the start-from-1 loop
  for (int i = 1; i < nums.length; i++) {
      if (nums[i] == nums[i - 1]) {
          // we are in a clump
          if (!inclump) {
              // this is the first time for this clump.
              inclump = true;
              clumpcnt++;
          }
      } else {
          inclump = false;
      }
  }
  return clumpcnt;
}


Table model code style This is my table model code style:

public class MyModel extends DefaultTableModel {

static Vector data = new Vector();
static Vector column = new Vector();
Connection conn;
Statement statement;
ResultSet result;

public MyModel() {
super(data, column);
try {
    conn = DriverManager.getConnection(...);
    statement = conn.createStatement();
    result = statement.executeQuery("Select * from table");

    int col = result.getMetaData().getColumnCount();
    for (int i = 1; i <= col; i++) {
        column.add(result.getMetaData().getColumnName(i));
    }

    while (result.next()) {
        Vector newRow = new Vector(col);
        for (int i = 1; i <= col; i++) {
            newRow.add(result.getString(i));
        }
        data.add(newRow);
    }

} catch (SQLException e) {
    e.printStackTrace();
}
}
// create methods for remove and add and edit a JTable selected row

}

//My GUI class that show jtable on own

Is this best way?

What is this way problems?

Any idea to be better?

This way your software is highly coupled. I can see three big responsibilities in it:

Get data from db
Format data in "TableModel way"
Create TableModel

Let's create a class to get data. I don't like the idea of let other classes deal with objects from jdbc api, so this class will format data too:

public class TableData {

    public TableContent getData() {
        Vector<String> headers = new Vector<String>();
        Vector<Vector<String>> content = new Vector<Vector<String>>();

        try {
            Connection conn = DriverManager.getConnection("");
            Statement statement = conn.createStatement();
            ResultSet rs = statement.executeQuery("Select * from table");

            headers = buildHeaders(rs);
            content = buildContent(rs);

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return new TableContent(headers, content);
    }

    private Vector<String> buildHeaders(final ResultSet rs) throws SQLException {
        Vector<String> headers = new Vector<String>();

        int col = rs.getMetaData().getColumnCount();
        for (int i = 1; i <= col; i++) {
            headers.add(rs.getMetaData().getColumnName(i));
        }
        return headers;
    }

    private Vector<Vector<String>> buildContent(final ResultSet rs) throws SQLException {
        Vector<Vector<String>> content = new Vector<Vector<String>>();

        while (rs.next()) {
            int col = rs.getMetaData().getColumnCount();
            Vector<String> newRow = new Vector<String>(col);

            for (int i = 1; i <= col; i++) {
                newRow.add(rs.getString(i));
            }
            content.add(newRow);
        }
        return content;
    }
}

I've created TableContent just to wrap the result:

public class TableContent {

    private final Vector<String> headers;
    private final Vector<Vector<String>> content;

    public TableContent(final Vector<String> headers, final Vector<Vector<String>> content) {
        this.headers = headers;
        this.content = content;
    }

    public Vector<String> headers() {
        return headers;
    }

    public Vector<Vector<String>> content() {
        return content;
    }
}

Now, the TableModel. That way you don't need to extend the class DefaultTableModel, you can simply instantiate one:

TableContent data = new TableData().getData();
new DefaultTableModel(data.headers(), data.content());

The class TableData still has a problem, the ideal would be to receive the Connection by the constructor, because without it, it's not possible to test the class with unit tests. I didn't wanna make the solution more difficult.


Android network API request I often use a similar scheme work with an API project. Can it be made easier, or is there a standard approach?

This class creates an API request:

public class ApiRequestCreator {

     private static String TEST_API_REQUEST = "http://jsonplaceholder.typicode.com/posts";

     public static Request createTestApiRequest(){
         return new Request.Builder()
                .url(TEST_API_REQUEST)
                .build();
     }
}

This class execute the request:

 public class ApiRequestExecutor {

     private final OkHttpClient client = new OkHttpClient();

     public void run(final Request request, final ApiMethodListener apiMethodListener) {

         new AsyncTask<Void, Void, String>() {

                @Override
                protected String doInBackground(Void ...voids) {
                try {
                     Response response = client.newCall(request).execute();
                     if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
                     return response.body().string();
                } catch (IOException e) {
                     e.printStackTrace();
                     return null;
                }
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                apiMethodListener.result(result);
            }

        }.execute();

    }
}

For all of this to start:

new ApiRequestExecutor().run(ApiRequestCreator.createTestApiRequest(), call_back_interface_here);

Your code looks good, but in my opinion AsyncTasks are good for single operations - it's not pleasant to make AsyncTask reusable. In my projects I use Ion to download some JSON data from API. This (and similar) library is prepared for making API calls, so it's easier and more ellegant to use for network requests.


Get specific lines from a huge text file I had a 50 Gb text file (ca. 45 mln lines) and needed to extract about 1500 lines from it. I knew their indices, that is, line numbers. Those 1500 lines were spread across the whole file up to the very end. To accomplish this, I wrote a simple Perl script. It worked and was quite fast: it finished in about 4-5 minutes on a low-end "business" laptop (but with an SSD).

Question 1: Is the code sensible and well-written?
Question 2: Could the performance be improved somehow?

#!/bin/perl
#
# Get lines from a file using line numbers from a second file
# Syntax
# getlinesfromfile.pl <source-file> <index-file> <output-file>
#
# Index file contains line numbers, one per line
# Example:
#
# 1
# 5
# 17
# 73
# 31337

use strict;
use warnings;

my $version = "1.0.4";
my $date_released = "4 December 2019";
print "\nGet lines from file. Version $version released on $date_released\n";

my ($source_file, $idx_file, $output_file) = @ARGV;
if (not defined $source_file or not defined $output_file or not defined $idx_file) {
    print "Parameters missing. Usage:\n\t$0 <source_file> <idx_file> <output_file>";
    exit;
}

open(my $i_fh, '<', $source_file)
    or die "FAILED to open '$source_file'!";
open(my $idx_fh, '<', $idx_file)
    or die "FAILED to open '$idx_file'!";
open(my $o_fh, '>', $output_file)
    or die "FAILED to open '$output_file'!";

# Read in indices
$/ = "\r\n";
my %indices;
while (my $line = <$idx_fh>) {
    chomp $line;
    $indices{$line} = 1;
}
close $idx_fh;
my $count_indices = scalar keys %indices;

my $msg_intro = <<"END";
Input filename: '$source_file'
Index filename: '$idx_file'
Output filename: '$output_file'

Indices: $count_indices

END

print $msg_intro;

my $lines_found = 0;
my $lines_parsed = 0;
$/ = "\n";
while (my $line = <$i_fh>) {
    chomp $line;
    $lines_parsed++;
    if (defined $indices{$lines_parsed}) {
        print $o_fh $line, "\r\n";
        $lines_found++;
    }
}
close $o_fh;
close $i_fh;
print ("Parsed $lines_parsed lines, found $lines_found matches.\n");

I know this might be a one time task, however, if you want to create a reusable code, I would always put the line counting code in a "continue" block. It is more readable and safer for future enhancements. Somehow the line increment code "finds itself" pushed after a next statement...

while (my $line = <$i_fh>) {
    chomp $line;
    if (defined $indices{$lines_parsed}) {
        print $o_fh $line, "\r\n";
        $lines_found++;
    }
} continue {
    $lines_parsed++;
}


Implementing Substring in C# I was trying just as a practice to implement substring on my own.

the Test is inside the Ctor just because it is easy.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    public class Substring
    {
        public Substring()
        {
            string test = "giladdarmonwhatareyoudoing";
            string res = ApplySubString(5, test);
            string res2 = ApplySubString2(5, test);
        }

        public string ApplySubString(int i, string test)
        {
            char[] charArray = test.ToArray();
            StringBuilder sb = new StringBuilder();

            for (; i < charArray.Length; i++)
            {
                sb.Append(charArray[i]);
            }
            return sb.ToString();
        }

        public string ApplySubString2(int i, string test)
        {
            char[] charArray = new char[test.Length - i];
            Array.Copy(test.ToCharArray(), i, charArray, 0, test.Length - i);
            return new String(charArray);
        }
    }
}

Please Let me know if you think I'm missing something or can offer a faster way.

Assorted things pop into my head here.

What's wrong with using the String.Substring(Int32) method?
At first glance, I would tend to think your 2nd method would be faster, but they really aren't the same.  If input i is greater than test.Length, the 2nd method will throw an exception but the first method would return an empty string.
I'd suggest having the test string be the first parameter since it's really the object that you are processing upon.  Plus you could then make them static extension methods to the input string.

EDIT - Adding extension method:

namespace System
{
    public static class GiladStrExt
    {
        public static string ApplySubString(this string value, int startIndex)
        {
            // You can invoke an extension method as a straight-up call,
            // e.g. GiladStrExt.ApplySubString(test, 5) and the value
            // for test could be null.
            if (value == null) throw new ArgumentNullException("value");
            if ((value.Length == 0) && (startIndex == 0)) return string.Empty;
            // Usually one uses the extension method with non-null values
            // so all we need to worry about is startIndex compared to value.Length.
            if ((startIndex < 0) || (startIndex >= value.Length)) throw new ArgumentOutOfRangeException("startIndex");
            var sb = new StringBuilder();
            for (int i = startIndex; i < value.Length; i++)
            {
                sb.Append(value[i]);
            }
            return sb.ToString();
        }
    }
}


Optimise many namedtuple assignment statements I'd just like to know if there's a way I can reduce the number of namedtuple assignment statements in the code below. The actual program has over 60 assignment statements and I feel like that could be optimised using some form of loop or maybe a function of some kind.

I'm not exactly sure how to do this myself, any advice?

The more pythonic the better, may I add. I'm using Python 3.6.

Here is a reduced section of my code:

from collections import namedtuple
import json

try:
    with open('assets/bin/units.bin', 'r') as file:
        units = json.load(file)
except:
    print('Could not load file.')

Unit = namedtuple('Unit', ['name', 'stats', 'type', 'population', 'cost', 'description'])
Unit.__doc__ += ': Stores data about a single unit, including Name, Stats, Type, Population and Cost.'

#Units(Infantry)
trooper = Unit(units[0]['name'],
               units[0]['stats'],
               units[0]['type'],
               units[0]['population'],
               units[0]['cost'],
               units[0]['description'])
robot = Unit(units[1]['name'],
             units[1]['stats'],
             units[1]['type'],
             units[1]['population'],
             units[1]['cost'],
             units[1]['description'])
commando = Unit(units[2]['name'],
                units[2]['stats'],
                units[2]['type'],
                units[2]['population'],
                units[2]['cost'],
                units[2]['description'])
flame_trooper = Unit(units[3]['name'],
                     units[3]['stats'],
                     units[3]['type'],
                     units[3]['population'],
                     units[3]['cost'],
                     units[3]['description'])
engineer = Unit(units[4]['name'],
                units[4]['stats'],
                units[4]['type'],
                units[4]['population'],
                units[4]['cost'],
                units[4]['description'])

#Units(Vehicles)
truck = Unit(units[5]['name'],
             units[5]['stats'],
             units[5]['type'],
             units[5]['population'],
             units[5]['cost'],
             units[5]['description'])
tank = Unit(units[6]['name'],
            units[6]['stats'],
            units[6]['type'],
            units[6]['population'],
            units[6]['cost'],
            units[6]['description'])
icv = Unit(units[7]['name'],
           units[7]['stats'],
           units[7]['type'],
           units[7]['population'],
           units[7]['cost'],
           units[7]['description'])
railgun = Unit(units[8]['name'],
               units[8]['stats'],
               units[8]['type'],
               units[8]['population'],
               units[8]['cost'],
               units[8]['description'])
missile_launcher = Unit(units[9]['name'],
                        units[9]['stats'],
                        units[9]['type'],
                        units[9]['population'],
                        units[9]['cost'],
                        units[9]['description'])

What if, instead of multiple variables, you would define a list of names, which you then use to create a dictionary of names to Unit instances which are initialized using dictionary unpacking:

names = [
    'trooper',
    'robot',
    'commando',
    'flame_trooper'
]
items = {
    name: Unit(**units[index])
    for index, name in enumerate(names)
}

Please think of better variable names for names and items.


Using Traits for set methods I have an abstract class Consumer:

abstract class Consumer
{
    const API_DOMAIN = 'https://test-api.com/v1/';

    private $client = null;
    private $credentials = [];

    public function __construct(array $credentials)
    {
        $this->client = new Client(); //This is GuzzleHttp/Client.
        $this->credentials = $credentials; // An array
    }

    abstract protected function getEndpoint();

    abstract protected function getHttpMethod();

    abstract protected function getParameter();

    abstract protected function getHeaders();

    abstract protected function getContent();

    abstract protected function parseResponse($result);

    protected function getUrl()
    {
        //This has to be fixed to accept an array of parameters: [key => value] format
        return implode('/', array_filter([self::API_DOMAIN, $this->getEndpoint(), $this->getParameter()]));
    }

    public function execute()
    {
        if (empty($this->credentials))
            throw new InvalidCredentialsException();
        try {
            $response = $this->client->request($this->getHttpMethod(), $this->getUrl(), [
                'auth' => $this->credentials,
                'form_params' => $this->getContent()
            ]);
            return $this->parseResponse(json_decode($response->getBody()->getContents()));
        } catch (\Exception $e) {
            throw new ErrorResponseException($e->getMessage(), $e->getCode());
        }
    }
}

And if I have an endpoint that needs to be accessed via GET I do the following:

class ListAll extends Consumer
{

    protected function parseResponse($result)
    {
        //Collection class from illuminate/support package
        //by the creators of Laravel.
        $collection = new Collection();
        foreach ($result as $item) {
            $collection->push(new Server($item));
        }
        return $collection;
    }

    public function getEndpoint()
    {
        return 'users';
    }

    public function getParameter()
    {
        return null; //No parameters required.
    }

    public function getHeaders()
    {
        return []; //No specific headers is going to be sent.
    }

    public function getContent()
    {
        return []; //No content is going to be sent.
    }

    public function getHttpMethod()
    {
        return 'GET';
    }
}

And the class above is pointing to an endpoint that requires no parameters, headers or content. However if it's a POST request (let's say the endpoint is for creating a user) I must have a set() method for content atleast. So I made a trait:

trait SetContentTrait
{
    protected $content = [];

    public function setContent($content)
    {
        $this->content = $content;
    }
}

And I'm using it in my Create class:

class Create extends Consumer
{
    use SetContentTrait;

    protected function parseResponse($result)
    {
        return new User($result);
    }

    protected function getEndpoint()
    {
        return 'users';
    }

    protected function getHttpMethod()
    {
        return 'POST';
    }

    public function getParameter()
    {
        return null;
    }

    public function getHeaders()
    {
        return [];
    }

    public function getContent()
    {
        return $this->content;
    }
}

Whenever I need to call that API I do the following:

$create = new Create($credentials);
$user = [
    'username' => 'Iv',
    'password' => 'SOMEHASH',
    'email' => 'my-email@gmai.com'
];

$create->setContent($user);
$user = $create->execute();

So is it a good approach to use traits in this case? Not every endpoint requires parameters, headers and content.

Your class names are a little generic, so it is hard for me to get a feel for your intent here. Create seems like an odd name for a class.  Maybe UserFactory, UserProvider or similar.  If Create is ultimately intended to be a more generic factory type of class that could create any sort of entity depending on what endpoint is used, then perhaps a name like EntityFactory or similar would be more appropriate. Try to name classes, methods, etc. to clearly indicate their purpose.
If you are getting advanced enough in your coding to start considering using traits, then you are advanced enough to write proper Doc blocks. Sorry, not trying to shame here, but this is generally well thought out code compared to many samples on this site. I want to see you take it to the next level in terms of being closer to production-ready code in a professional environment.
Consider implementing concrete methods (which could be overridden) in your abstract class. You are repeating yourself a lot in extending classes with implementing your getters.
So do you have a second use case where you are going to use that trait?  It probably doesn't make sense to make a trait unless you have other use cases where you need to consume it.   For this single use case you show here, I don't know why this functionality would not just be part of base class.
From a coding style standpoint, you are doing a few thiings that are generally frowned upon.  You are putting comments out to the right of code instead of above the code they are applicable to, and you have several lines the go beyond the typical "best practice" of keeping lines of code to an 80 character limit.  These make code harder to read.

Some more specific comments follow:

const API_DOMAIN = 'https://test-api.com/v1/';

Why is this a constant on this class? If you want to make this class more flexible, perhaps it is passed on constructor or set via setter.  If this is very narrow use class, perhaps at least consider moving this to app configuration.

public function __construct(array $credentials)
{
    $this->client = new Client(); //This is GuzzleHttp/Client.
    $this->credentials = $credentials; // An array
}

Can these credentials be passed in an object that can be better type hinted? You should take appropriate steps to validate this $credentials parameter as a valid dependency (and throw Exception if it is not) before working with at and setting it on the object. Perhaps throw InvalidArgumentException upon validation failure.

Consider passing the Guzzle client to constructor as dependency (dependency injection). Why should this class need to know how to instantiate its own dependencies and the potential error/exception handling around them (which is absent here) in order to work with the dependency?  It should just get a valid dependency this is properly set up for it to begin working with.

Get in good habit of namespacing.  Wherever you instantiate the guzzle client you should do it like  new \GuzzleHttp\Client(). This is much clearer (eliminates the need for your comment).  Similarly if passing as a dependency, you should type hint as \GuzzleHttp\Client $guzzle_client.

protected function getUrl()
{
    //This has to be fixed to accept an array of parameters: [key => value] format
    return implode('/', array_filter([self::API_DOMAIN, $this->getEndpoint(), $this->getParameter()]));
}

Do you really need to go through this exercise every time or should Url just be set on object?

if (empty($this->credentials))
    throw new InvalidCredentialsException();

As mentioned previously, this should have been validated in the constructor and failed long before the point where a client would ever call this method.

         return $this->parseResponse(json_decode($response->getBody()->getContents()));

Odd to see a return within a try block. Does this code even potentially throw?
There really is too much going on in a single line of code and REALLY assumes a happy path operation of all 4 underlying operations.  There might be need to better handling of edge cases here (what if JSON doesn't decode? what if "parsing" doesn't work?).

    } catch (\Exception $e) {
        throw new ErrorResponseException($e->getMessage(), $e->getCode());
    }

This is kind of a meaningless try-catch block. It takes a more generic exception type and turns it into a more specific exception (an odd pattern in and of itself), but doesn't really do anything meaningful here like log the failure or add additional context to the underlying exception to the caller.  How is this any better than the caller just getting the underlying Exception directly?

    $collection = new Collection();
    foreach ($result as $item) {
        $collection->push(new Server($item));

Namespaces?

protected function getEndpoint()
{
    return 'users';
}

protected function getHttpMethod()
{
    return 'POST';
}

Endpoint, HttpMethod, headers, content, etc. are acting here as de facto class constants or properties when you do something like return 'some hard coded value';.

These should be actual class properties or constants.  This probably also removes the need to override these methods in every implementing class (if you put concrete methods in base class) as well as need to define some subset of these as traits.


Codable Failure Response Handler Suppose You have two kind of response like one for success and one for failure

Success response model will looks like

struct UserLogin: Codable {
    let status: Bool?
    let accessToken: String?
    let data: [UserLoginData]?
   ....
}

Failure Model will looks like

struct FailedResponse: Codable {
    let status: Bool?
    let error: ErrorResponse?

}

How I handle this two responses

struct FailableResponse <T:Codable,E:Codable> : Codable {

    var success:T?
    var failure:E?

    public init(from decoder:Decoder) throws {

        let singleValue = try decoder.singleValueContainer()

        success = try singleValue.decode(T.self)
        failure = try singleValue.decode(E.self)

    }
}

And How I use FailableResponse

  APIClient.login(userName: self.loginViewModel.userName, password: self.loginViewModel.password) { (response:FailableResponse<UserLogin,FailedResponse>? , error) in

   }

// METHOD OF API CLIENT
// API CALLING
static func login<T:Codable>(userName:String,password:String,completion:@escaping completionResponse<T>) {
        self.performRequest(request: APIRouterUserModule.login(email: userName, password: password)) {(model) in

            self.handleResponseCallCompletion(result: model, completion: completion)
        }
  }
 // Parsing
 private static func handleResponseCallCompletion<T:Codable>(result:Result<Any>,completion:@escaping completionResponse<T>) {
        let object = CodableHelper<T>().decode(json: result)
        completion(object.object,object.error)
    }

I think It can be more better

Any suggestion Please :)

There are two approaches

For the sake of completeness, I’ll describe the typical, simple solution:

struct UserLoginResponse: Codable {
    let status: Bool
    let error: ErrorResponse?
    let accessToken: String?
    let data: [UserLoginData]?
}

The status is not optional (because it’s presumably there regardless). But you can just decode this struct:

do {
    let responseObject = try decoder.decode(UserLoginResponse.self, from: data)
    switch responseObject.status {
    case true:
        guard let accessToken = responseObject.accessToken, let userLoginData = responseObject.data else {
            throw ParsingError.requiredFieldMissing
        }

        // use accessToken and userLoginData here

    case false:
        guard let errorObject = responseObject.error else {
            throw ParsingError.requiredFieldMissing
        }

        // use errorObject here
    }
} catch {
    print(error)
}

If you really want to do this generic, wrapper approach, I’d suggest a slight refinement. Notably, the code in your question returns an object for which both the success and error objects are optionals. (There seem like there are a lot of ? thrown in there quite liberally, whereas most API dictate “if success, x and y will be present, if failure, z will be present”.)

I’d suggest, instead, a pattern that captures the fact that the response will be either success (when status is True) or failure (when status is False), and rather than returning both success and failure objects as optionals, use the Result<Success, Failure> enumeration with associated values, which is included in Swift 5. Or, if you’re using an earlier version of Swift, you can define it yourself:

enum Result<Success, Failure> {
    case success(Success)
    case failure(Failure)
}

Then, the API response wrapper can have a non-optional result property of type Result<T, E>, where:

If status is True, parse the success object as a non-optional associated value which is the Success type;
If status is False, parse the error object as a non-optional associated value which is the Failure type;

Thus:

struct ApiResponse<T: Codable, E: Codable>: Codable {
    let status: Bool
    var result: Result<T, E>
    var error: E?

    enum CodingKeys: String, CodingKey {
        case status, error
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        status = try values.decode(Bool.self, forKey: .status)
        if status {
            let singleValue = try decoder.singleValueContainer()
            result = try .success(singleValue.decode(T.self))
        } else {
            let parsedError = try .failure(values.decode(E.self, forKey: .error))
            error = parsedError
            result = .failure(parsedError)
        }
    }
}

Then you can do:

do {
    let responseObject = try decoder.decode(ApiResponse<UserLoginResponse, ErrorResponse>.self, from: data)
    switch responseObject.result {
    case .success(let object):
        print(object.accessToken, object.data)

    case .failure(let error):
        print(error)
    }
} catch {
    print(error)
}

This would seem to better capture the true nature of the response, that it’s either successful (and you get the non-optional success object) or it’s a failure (and you get the non-optional ErrorResponse object).

By the way, I’d suggest that in this scenario, that UserLoginResponse be updated to reflect which fields are truly optional and which aren’t. For example, if you know that if status is True, that both accessToken and data will be present, then I’d make those non-optional properties:

struct UserLoginResponse: Codable {
    let accessToken: String
    let data: [UserLoginData]
}


Percentage of questions that are unanswered or answered I put together this simple query which calculates the total percentage of answered questions and unanswered questions. The formulas used to calculate these are shown below:

$$
\text{Answered Percentage} = 100 - \left(\frac{\text{Unanswered}}{\text{Answered}} \times 100\right) \\
\text{Unanswered Percentage} = \frac{\text{Unanswered}}{\text{Answered}} \times 100
$$

Finally, here's the source:

DECLARE @TotalQuestions DECIMAL = (
  SELECT COUNT(*) FROM Posts
);

DECLARE @UnansweredQuestions DECIMAL = (
  SELECT COUNT(*) FROM Posts WHERE AnswerCount = 0
);

-- The percentage of un-answered questions. Calculated
-- using this:
  -- (Unanswered Questions / Total Site Questions) * 100
SELECT
  (@UnansweredQuestions / @TotalQuestions) * 100.0
AS [Percentage Of Unanswered Questions];

-- The percentage of answered questions. Calculated
-- using this:
  -- 100 - ((Unanswered Questions / Total Site Questions) * 100)
SELECT
  100 - ((@UnansweredQuestions / @TotalQuestions) * 100.0)
AS [Perentage Of Answered Questions];

Comments
Your comments are mostly clutter, and I mean that because your naming is good enough to where the comments are mostly irrelevant. Also, if you do need to make multi-line comment, you can use the same syntax in SQL as in pretty much everything else.
Look at this, the comments and the code read almost identically:

/**
 * The percentage of un-answered questions. Calculated
 * using this:
 * (Unanswered Questions / Total Site Questions) * 100
 */
SELECT
  (@UnansweredQuestions / @TotalQuestions) * 100.0 AS [Percentage Of Unanswered Questions];

There is an elegant way of assigning an alias in an expression that would make it even easier to read:
SELECT
  [Percentage Of Unanswered Questions] = (@UnansweredQuestions / @TotalQuestions) * 100.0

Does exactly the same thing, but reads more like typical code, where you name a thing before assigning it something, rather than after.

Dead code
Your first SELECT query is never displayed. There are two ways you could fix that, either by making them two different columns, or two different rows (according to your needs).
Columns:
SELECT
  [Percentage Of Unanswered Questions] = (@UnansweredQuestions / @TotalQuestions) * 100.0
, [Perentage Of Answered Questions] = 100 - ((@UnansweredQuestions / @TotalQuestions) * 100.0);

Rows:
SELECT
  [Type of value] = 'Percentage Of Unanswered Questions'
  , [Value] = (@UnansweredQuestions / @TotalQuestions) * 100.0
UNION
SELECT
  'Percentage Of Answered Questions'
  , 100 - ((@UnansweredQuestions / @TotalQuestions) * 100.0);


Finding the number of pairs in an integer Array This function returns the number of pairs of the same elements in the array

It takes, array length and the array as the parameter

    n: Length of array

    ar: Array of integers for example

    4 6 7 8 7 6 6 7 6 4

  returns 4

fun getNumberOfPairs(n: Int, ar: Array<Int>): Int {
    val enteries = HashSet<Int>()
    var pairs = 0

    for (i in 0 until n) {
        if (!enteries.contains(ar[i])) {
            enteries.add(ar[i])
        } else {
            pairs++
            enteries.remove(ar[i])
        }
    }

    println(pairs)
    return pairs
}

How can we write this code in a better way for readability/performance?

Overall it's very readable and fast already. Good job.

I have some suggestions for possible improvements:

As n must be equal to ar.size, you could drop that parameter from the method and use ar.size in place of n within the method body.
This method is a pure function except for the side effect of printing the result. Being a "pure function" is often a good thing so you can move the printing of the result to outside the method. Printing something is also quite time-consuming.
Your method could easily support more than Int, it doesn't have to be restricted by a specific type. You could check for duplicates of any type so we can make this method generic.
As you are iterating over elements you could use for (e in ar) instead of iterating over the indexes with for (i in 0 until n). This would make it more efficient for data structures that doesn't have a \$O(1)\$ lookup-time, for example LinkedList.
The method HashSet.add returns false if the value already exists, so you don't need the call to .contains.
There is a typo in the name enteries, it should be called entries.
ar could be called input to make it more readable.

After applying all of the above, this is what you would end up with:

fun <T> getNumberOfPairs(input: Array<T>): Int {
    val entries = HashSet<T>()
    var pairs = 0

    for (e in input) {
        if (!entries.add(e)) {
            pairs++
            entries.remove(e)
        }
    }
    return pairs
}


Apache POI and cyclomatic complexity of code I have an Excel file, which I am reading using Apache POI APIs; which gives me control over cells/columns in my Excel.

I have around 17 columns in my Excel and these are with different datatypes. I want to populate a model object from these column values. So, I came up with something like below to populate my model object:

private WHTApps populateModel(WHTApps whtApp, int columnIndex, Object cellValue) {
        switch (columnIndex) {
        case 0:
            whtApp.setVendorCode((int) cellValue);
            break;
        case 1:
            whtApp.setVendorName((String) cellValue);
            break;
        case 2:
            whtApp.setCountry((String) cellValue);
            break;
        case 3:
            whtApp.setApplicationReceivedFromUSDate((Date) cellValue);
            break;
        case 4:
            whtApp.setContractNumber((String) cellValue);
            break;
        case 5:
            whtApp.setContractEffectiveDate((Date) cellValue);
            break;
        case 6:
            whtApp.setContractExpirationDate((Date) cellValue);
            break;
        case 7:
            whtApp.setAutomaticRenewal((String) cellValue);
            break;
        case 8:
            whtApp.setReducedRate((int) cellValue);
            break;
        case 9:
            whtApp.setForm17((String) cellValue);
            break;
        case 10:
            whtApp.setResidencyCertIssueDate((Date) cellValue);
            break;
        case 11:
            whtApp.setTaxAuthoritySubmissionDate((Date) cellValue);
            break;
        case 12:
            whtApp.setTaxAuthorityAcceptanceDate((Date) cellValue);
            break;
        case 13:
            whtApp.setStatus((String) cellValue);
            break;
        case 14:
            whtApp.setForm17Expiration((Date) cellValue);
            break;
        case 15:
            whtApp.setComments((String) cellValue);
            break;
        case 16:
            whtApp.setRemarks((String) cellValue);
            break;
        case 17:
            whtApp.setCategory((String) cellValue);
            break;
        default:
        }

        return whtApp;
    }

But, this gives rise to a really high cyclomatic complexity value of 19.

Now how do I reduce the cyclomatic complexity as I have 17 columns which I need to populate in my model object?

If you want to create an object from Excel row you can change the method's signature to accept an array of values:

private WHTApps createModelFromValues(Object[] values) {
    WHTApps whtApp = new WHTApps();
    whtApp.setVendorCode((int) values[0]);
    whtApp.setVendorName((String) values[1]);
    ....
    whtApp.setCategory((String) values[17]);
    return whtApp;
}

This method is not as complex as the first one and is easier to test. Client code will have to populate an array of values to pass.

You should consider adding some kind of error checking: validate values array before processing it. Check for length and data type errors. You can create a custom exception class that will clearly show where the problem is.

Probably, you can make this code more flexible by adding a separate mapper class that will set properties using reflection. I'm not sure if it's worth the effort in this particular case, though.


Optimizing code to find maximum XOR in Java This problem is from HackerRank (not a competition, just for practice)

Basically what you do is take in two integers as a range and then finding the maximum XOR from a pair of integers in that interval.

Here is my code for doing so (it passed all the test cases):

static int maxXor(int l, int r) {
    int maxXor = l ^ r;
    for(int left=l;left<=r; left++) {
        for(int right=l;right<=r; right++) {
            if((left ^ right) > maxXor) {
                maxXor = left ^ right;
            }
        }
    }
    return maxXor;
}

I was able to tell that this code segment runs in \$\mathcal{O}(n^2)\$ because the outer for loop will run in \$\mathcal{O}(N)\$, \$N\$ as in number of integers in the range, and the inner loop will also run in \$\mathcal{O}(N)\$. Because each time the outer loop runs, the inner loop runs one time aswell, the entire code segment will in \$\mathcal{O}(N^2)\$. Is that good analysis?

But anyways, is there an optimization (for performance) for this code segment to get the runtime down to \$\mathcal{O}(N)\$ or \$\mathcal{O}(log N)\$ perhaps?

You are correct that your code has \$\mathcal{O}(n^2)\$ performance.

Here is a solution in \$\mathcal{O}(log(n))\$:

static int maxXor(int l, int r) {
    int c = 0;
    int exp = 0;
    while (l != 0 || r != 0) {
        c++;
        if ((l & 1) != (r & 1)) {
            exp = c;
        }
        l >>= 1;
        r >>= 1;
    }
    return (1 << exp) - 1;
}

Explanation

The task of finding the maximum XOR value \$m\$ is equivalent to finding the most significant bit \$b\$ that differs between L and R. The maximum XOR value will be \$m=2^{b+1}-1\$.

Proof sketch

Let's use the number 42 (101010) and 59 (111011) as a running example. The most significant bit that differs is bit 4, therefore we expect \$m=31\$.

vvvvvv all these bits are equal
00000101010
00000111011
      ^ bit b=4 differs

Note that bits above \$b\$ never change when counting from L to R, and since XOR only cares about different bits we have \$m<2^{b+1}\$ as an upper bound.

But since bit \$b\$ is set in R and not set in L, there have to be two numbers in the range [L, R] where:

In the first number x, all bits below \$b\$ are set.
In the second number x+1, \$b\$ is set, but all bits below it are not.

So x XOR x+1 will be equal to the sum of all bits up to and including \$b\$ which is \$2^{b+1}-1\$, i.e. \$m \geq 2^{b+1}-1\$.

Thus we have \$2^{b+1}-1 \leq m < 2^{b+1}\$

=> \$m = 2^{b+1}-1\$

In the example:

47 101111
48 110000
47 XOR 48 = 31