JavaScript card game and hand evaluation I have the following code (it looks long but it's not too bad):

function evaluate_cards(hand){
    var hand_length = hand.length;
    var num_of_sets = 0;
    var num_of_runs = 0;
    var cards_in_run = 0;
    var suit = '';
    var buckets = {
         three_bucket: [],
         four_bucket: [],
         five_bucket: [],
         six_bucket: [],
         seven_bucket: [],
         eight_bucket: [],
         nine_bucket: [],
         ten_bucket: [],
         j_bucket: [],
         q_bucket: [],
         k_bucket: [],
         w_bucket: [] //bucket for wilds
    }

    for(var i = 0; i < hand_length; i++){
        if(hand[0].is_wild){
            buckets.w_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 3){
            buckets.three_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 4){
            buckets.four_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 5){
            buckets.five_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 6){
            buckets.six_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 7){
            buckets.seven_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 8){
            buckets.eight_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 9){
            buckets.nine_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 10){
            buckets.ten_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 11){
            buckets.j_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 12){
            buckets.q_bucket.push(hand.splice(0, 1));
        }else if(hand[0].value == 13){
            buckets.k_bucket.push(hand.splice(0, 1));
        }
    }

    for(var k in buckets){
        if(buckets.hasOwnProperty(k)){
            if(buckets[k].length >= 3 && buckets[k] != buckets.w_bucket){
                num_of_sets++;
            }else if(buckets.w_bucket.length > 0 && buckets[k].length == 2){
                buckets[k].push(buckets.w_bucket.shift());
                num_of_sets++;
            }else if(buckets[k].length < 3 && buckets.w_bucket.length > 1){
                    for(var i = 0; i < buckets.w_bucket.length; i++){
                        buckets[k].push(buckets.w_bucket.shift());
                    }
                    if(buckets[k].length >= 3){
                        num_of_sets++;
                    }
            }else if(num_of_sets == 0){
                if(buckets[k].length > 0){
                    if(suit == ''){
                        suit = buckets[k][0].suit;
                    }else if(suit == buckets[k][0].suit){
                        cards_in_run++;
                    }else{
                        suit = '';
                    }
                    if(cards_in_run != 0 && cards_in_run < 3 && buckets.w_bucket.length != 0){
                        cards_in_run++;
                    }
                }
                if(cards_in_run >= 3){
                    num_of_runs++;
                    cards_in_run = 0;
                }
            }
        }
    }
    return {'runs':num_of_runs, 'sets': num_of_sets};
}

It's based off of the second answer to this question on game-dev.se. There are two major differences, however.

There are wilds in my game, which makes finding things like runs much more difficult.
Most sets/runs are going to be 3 or four cards but could be up to 5 cards, obviously anything 6 and over can be divided (set or run has to be a minimum of 3 cards).

The following is passed a hand will determine almost all sets of three cards, but only a few runs.

My request is that it be reviewed for optimization and where my logic goes wrong with runs. I'm totally open to any suggestions.

Your sorting of cards to buckets takes a lot of code, which is because the names of your buckets don't match with the names of cards. The cards have just numeric values (10, 11), while buckets are named with words (ten_bucket, j_bucket). I would represent the cards as such:

{kind: 3, suit: "club"},
{kind: 10, suit: "heart"},
{kind: "K", suit: "spade"},
{wild: true},

And then I could write a much simpler algorithm for putting them to buckets:

var wilds = [];
var kinds = {3:[], 4:[], 5:[], 6:[], 7:[], 8:[], 9:[], 10:[], J:[], Q:[], K:[]};

hand.forEach(function(card) {
    if (card.wild) {
        wilds.push(card);
    } else {
        kinds[card.kind].push(card);
    }
});

I'm also handling the wild cards as a completely separate category, which makes it much easier to check if we have three-of-a-kind:

for (var k in kinds){
    if (kinds.hasOwnProperty(k)){
        if (kinds[k].length + wilds.length >= 3) {
            // Yes, we have a three-of-a-kind
        }
    }
}

Checking for runs

A basic check for runs is quite simple. You just loop through all the buckets in order and check for the longest sequence without holes:

function longest_run() {
    var count = 0;
    var max_run = 0;
    ["3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"].forEach(function(k) {
        if (kinds[k].length >= 1) {
            count += 1;
        } else {
            if (count > max_run) {
                max_run = count;
            }
            count = 0;
        }
    });
    return max_run;
}

But taking the wild cards into account complicates the whole thing considerably. Now it really becomes a question of combinatorics. A brute-force approach would be to try using the wildcards in each of the empty positions. This can be optimized of course, but I suggest you turn to StackOverflow with this question - some math-minded people might be able to provide you with a better algorithm over there.


News feed python script The task: user-generated news feed:

User select what data type he wants to add

Provide record type required data

Record is published on text file in special format

Types of data:

News – text and city as input. Date is calculated during publishing.

Private ad – text and expiration date as input. Day left is calculated during publishing.

Your unique one with unique publish rules.

Expected result:
News -------------------------
Something happened
London, 03/01/2021 13.45
------------------------------

News -------------------------
Something other happened
Minsk, 24/01/2021 20.33
------------------------------

Private Ad ------------------
I want to sell a bike
Actual until: 01/03/2021, 21 days left
------------------------------

Joke of the day ------------
Did you hear about the claustrophobic astronaut?
He just needed a little space
Funny meter – three of ten
------------------------------

My code:
from datetime import datetime, date
from sys import exit

class Article:
    def __init__(self, title, text, line_width):
        self.title = title
        self.text = text
        self.line_width = line_width

    @staticmethod
    def publish_article(formatted_text):
        with open("all_news.txt", "a") as file:
            file.write(formatted_text)

class News(Article):
    def __init__(self, title, text, city, date, line_width):
        Article.__init__(self, title, text, line_width)
        self.city = city
        self.date = date

    def format_text(self):
        return f"{self.title}{(self.line_width - len(self.title)) * '-'}\n"\
               f"{self.text} \n"\
               f"{self.city}, {self.date.strftime('%d/%m/%Y %H:%M:%S')} \n"\
               f"{'-'*self.line_width}\n\n\n"

class Ad(Article):
    def __init__(self, title, text, end_date, line_width):
        Article.__init__(self, title, text, line_width)
        self.end_date = end_date

    def format_text(self):
        day, month, year = map(int, self.end_date.split('/'))
        days_left = (date(year, month, day) - date.today()).days
        return f"{self.title}{(self.line_width - len(self.title)) * '-'}\n"\
               f"{self.text} \n"\
               f"Actual until: {date(year, month, day).strftime('%d/%m/%Y')}, {days_left} days left \n"\
               f"{'-'*self.line_width}\n\n\n"

class PersonalNews(Article):
    def __init__(self, title, text, line_width):
        Article.__init__(self, title, text, line_width)

    def format_text(self):
        return f"{self.title}{(self.line_width - len(self.title)) * '-'}\n"\
               f"{self.text} \n"\
               f"{'-'*self.line_width}\n\n\n"

while True:
    user_input = input('Enter a number: '
                       '1 - Publish news;\n'
                       '2 - Publish ad; \n'
                       '3 - Publish personal news\n'
                       'q - Exit\n')
    if user_input == "1":
        new_news = News("News",
                        input('Print your text\n'),
                        input('Print city for the news\n'), datetime.now(), 30)
        new_news.publish_article(new_news.format_text())
    elif user_input == "2":
        new_news = Ad("Private Ad",
                      input("Input your text\n"),
                      input('Print endDate of ad in format DD/MM/YEAR\n'), 30)
        new_news.publish_article(new_news.format_text())
    elif user_input == "3":
        new_news = PersonalNews(input("Input your title\n"),
                                input("Input your text\n"), 30)
        new_news.publish_article(new_news.format_text())
    elif user_input == "q":
        exit(0)
    else:
        print("Incorrect input. Please enter a number (1, 2, 3) or 'q' for exit")

Shadowing
Your date parameter to the constructor of News is poorly-named, because it shadows the built-in date that you've imported from datetime.
Super
Your call to Article.__init__() should use super() instead.
Data classes
Article can just be a @dataclass with its explicit __init__ removed.
Static methods
publish_article doesn't make sense as a static method. In your invocations, you're always calling format_text() on a child instance, then passing that to a static method on the parent. Instead:

Define format_text(self) -> str: raise NotImplementedError() on Article to declare it abstract
Change publish_article(self) to simply file.write(self.format_text())

Backslash continuation
Change this:
    return f"{self.title}{(self.line_width - len(self.title)) * '-'}\n"\
           f"{self.text} \n"\
           f"{self.city}, {self.date.strftime('%d/%m/%Y %H:%M:%S')} \n"\
           f"{'-'*self.line_width}\n\n\n"

to drop the backslashes and use parens instead:
    return (
        f"{self.title}{(self.line_width - len(self.title)) * '-'}\n"
        f"{self.text} \n"
        f"{self.city}, {self.date.strftime('%d/%m/%Y %H:%M:%S')} \n"
        f"{'-'*self.line_width}\n\n\n"
    )

Date parsing
This is evil:
    day, month, year = map(int, self.end_date.split('/'))

Instead, you should be using an actual parsing method out datetime to get you a date instance; then referring to its members. Since you're looking for DD/MM/YEAR, this will be:
end_date = datetime.strptime(self.end_date, '%d/%m/%Y').date()
# Use end_date.day, end_date.month, end_date.year

That said, if you're at all able, drop that date format like a sack of rotten potatoes. YYYY-mm-dd is sortable and unambiguous.


Calculate simple arithmetic string in Scala Problem

Given an arithmetic string like 2+2*3 calculate result 8.

Assumptions you can make

string will be always well formed (no error checking needs to be done)
only operators passed in string will be + and *
only single digit numbers allowed

Example

input = 2*2*2+2*1*5
output = 18

input = 2+2*3
output = 8

Hers is scala code for the same

object Expression extends App {
  implicit class Converter(char: Char) {
    def toNum: Int = char - '0'
  }

  def evaluateExpression(s :List[Char]): Int = {
    s match {
      case left::op::List(right) =>  // a+b or a*b
        op match {
          case '+' =>  left.toNum + right.toNum
          case  _ =>   left.toNum * right.toNum
        }
      case left::op::right => // a+b*c or a*b+c
         op match {
           case '+' =>
             left.toNum + evaluateExpression(right)
           case '*' =>
             val nextAdd = right indexOf '+'
             val (multiplication ,pendingExpression) = if (nextAdd == -1) {
                                                         (right,List[Char]())
                                                       } else {
                                                         (right.take(nextAdd), right.drop(nextAdd + 1))
                                                       }
             val product = (multiplication.filter( _ != '*') map (_.toNum)).foldLeft(left.toNum) (_ * _)
             if (pendingExpression.isEmpty) product
             else product + evaluateExpression(pendingExpression)
          }
     }
   }
  List("3*3*3", "2+2*3", "0*0*1", "0+0*1", "0*0*1", "2+2*3*3", "2+2+2*3+2+2") foreach { expr =>
    println(expr + " = " + evaluateExpression(expr.toList))
  }
}

Output for above code

3*3*3 = 27
2+2*3 = 8
0*0*1 = 0
0+0*1 = 0
0*0*1 = 0
2+2*3*3 = 20
2+2+2*3+2+2 = 14

You might want to spend some time becoming more familiar with the Standard Library. You're doing a few things that are already provided for.

implicit class Converter(char: Char) {
  def toNum: Int = char - '0'
}

To convert a digit character into the value it represents: char.asDigit. If you have one or more digit characters in a string: digits.toInt

Your solution also fails for expressions like "2*2+3". It looks like the evaluateExpression() code doesn't anticipate that, in the recursive call evaluateExpression(pendingExpression), the value of pendingExpression might be a single digit.

But mostly, with the input under so many tight restrictions, you should consider what shortcuts might be available to you.

def evaluateExpression(s :String) :Int =
  s.split("\\+")
   .map(_.split("\\*")
         .map(_.toInt)
         .product)
   .sum


Super class knowing the type of its children? Surely there is a better way I'm working on a small project that does mathematical calculations based on selected data in a JTable. The goal is to make the program fairly adaptable for adding new mathematical calculations in the future. For reference, some of the current calculations are: calculating the mean (average) of a set of data; calculating the percentile of each item in a set of input data; calculating the least squares linear regression (best fit linear function) for a set of data points.

My current design thought process is that to make things the math utilities flexible, there needs to be a some type of base class for analysis data that serves as input and output to some type of performAnalysis function in a base class for all analysis classes. This lead me to a skeleton design as follows:

public enum AnalysisDataType {
    Scalar,
    Set,
    Map
}

public interface IAnalysisData {
    AnalysisDataType getType();
}

public interface IAnalaysisDataScalar extends IAnalysisData {
    double getValue();
}

public interface IAnalaysisDataSet extends IAnalysisData {
    int getCount();
    IAnalysisData getData(int index);
}

public interface IAnalaysisDataMap extends IAnalysisData {
    IAnalysisData getDomain();
    IAnalysisData getCodomain();
}

public interface IDataAnalysis {
    AnalysisDataType getInputDataType();
    AnalysisDataType getOutputDataType();

    IAnalysisData performAnalysis(IAnalysisData inputData);
}

Then, something for calculating mean would be:

public class DataAnalysisMean implements IDataAnalysis {
    AnalysisDataType getInputDataType() { return AnalysisDataType.Set; }
    AnalysisDataType getInputDataType() { return AnalysisDataType.Scalar; }

    IAnalysisData performAnalysis(IAnalysisData intputData) {

        IAnalysisDataSet inputDataSet = (IAnalysisDataSet)inputData;
        double sum = 0;

        for (int i = 0; i < inputDataSet.getCount(); i++) {
            IAnalysisData dataItem = inputDataSet.getData(i);
            IAnalysisDataScalar dataItem = (IAnalysisDataScalar)dataItem;
            sum += dataItem.getValue();
        }

        return new IAnalysisDataScalar() {
            @Override
            double getValue() {
                return sum / inputDataSet.getCount();
            }

            @Override
            AnalysisDataType getType() {
                return AnalysisDataType.Scalar;
            }
        };
    }
}

I realize a little more work needs to go into "describing" the input and output data items because no where did I mention that the input set contained scalars, but - while I already have an idea how to solve that one - I feel that the whole approach is hackish.

The thought behind this approach is that the code using interfacing with these math utilities could query the IDataAnalysis interface to determine what the expected input and output is and can send the appropriate input as needed and parse the results appropriately. This would allow us to just need to drop-in more functionality at a later time without having to add additional controller logic to tie it in.

I feel like its wrong for a parent class - or interface in this case - to know about its possible children classes (interfaces) through the AnalysisDataType enum and the getType method. As always with OO programming, surely just another layer of abstraction or some type is needed, though perhaps I'm just missing out on some other design pattern that solves this exact problem.

Anyway, if anyone has advice on what I might do to better organize this, I'd much appreciate it. I'd love to hear how wrong my thoughts are and learn a better way.

First, I get some error messages when I put this in the compiler.
I had to replace the anonymous inner class that is returned by performAnalysis with a helper class. I'm not a fan of helper classes like this, so it would be nice if someone else had a better idea.

Second, I'm thinking generics would solve this quite nicely.
I agree that the parent class should not need to know it's child classes, but it can obtain this data; see the methods that I have commented out. I have commented them out because I don't like them, but still want to show that it's possible. I'll admit that using .class is a bit tricky when using generics, because of type erasure. However, as long as the generic types are known at compile time, this should not be a problem.

interface IDataAnalysis<InputType extends IAnalysisData, OutputType extends IAnalysisData> {

//    public Class<?> getInputDataType( );
//    public Class<?> getOutputDataType( );

    OutputType performAnalysis(InputType inputData);
}

public class DataAnalysisMean implements IDataAnalysis<IAnalysisDataSet, IAnalysisDataScalar> {

//
//    public Class<?> getInputDataType( ) { return IAnalysisDataSet.class; }
//    public Class<?> getOutputDataType( )  { return IAnalysisDataScalar.class; }

public IAnalysisDataScalar performAnalysis(IAnalysisDataSet inputData) {

    IAnalysisDataSet inputDataSet = (IAnalysisDataSet)inputData;
    double sum = 0;

    for (int i = 0; i < inputDataSet.getCount(); i++) {
        IAnalysisData dataItem = inputDataSet.getData(i);
        IAnalysisDataScalar dataItem2 = (IAnalysisDataScalar)dataItem;
        sum += dataItem2.getValue();
    }

    return new HelperClass( inputDataSet, sum );
}

private class HelperClass implements IAnalysisDataScalar
{
    IAnalysisDataSet inputDataSet;
    double sum = 0;

    HelperClass( IAnalysisDataSet inputSet, double sum )
    {
        this.inputDataSet = inputSet;
        this.sum = sum;
    }

    @Override
    public double getValue() {
        return sum / inputDataSet.getCount();
    }

    @Override
    public AnalysisDataType getType() {
        return AnalysisDataType.Scalar;
    }
   }
}


A pseudo universal data encoder This is useful for web scraping and web crawling anything other than that idk. It seems to work as planned.

I'm curious as to how the community thinks about the way I break the code down into simple functions with descriptive names. My reasoning for writing so many trivial functions is that I think it makes the code read more like pseudo code. In my opinion it makes the code self documented and easier to read. It also adds a big reusability factor.

#-*-coding:utf8;-*-
#qpy:3
#qpy:console

def is_string(data):
    return isinstance(data, str)

def is_bytes(data):
    return isinstance(data, bytes)

def encodeable(data):
    return is_string(data) or is_bytes(data)

def encode_decode(data, *args, **kw):
    kw.setdefault('errors', 'ignore')
    return data.encode(*args, **kw).decode(*args, **kw)

def encode(data, encoding='ascii', **kw):
    if not encodeable(data):
        error_msg = ('Invalid data type',
                         'to_ascii can only encode',
                         'bytes, strings, and raw-strings',
                         'not {}'.format(type(data)))
        raise ValueError(error_msg)

    if is_string(data):
        data = encode_decode(data, encoding, **kw)

    elif is_bytes(data):
        data = data.decode(encoding, **kw)

    return data

def test_encode():
    #invalid = to_ascii({})
    s = str('spam')
    r = r'eaggs'
    b = b'slurm'
    print('Before encoding')
    print(s, r, b)
    print(type(s), type(r), type(b), '\n')

    print('After encoding')
    s, r, b = encode(s), encode(r), encode(b)
    print(encode(s), encode(r), encode(b))
    print(type(s), type(r), type(b))

if __name__ == '__main__':
    test_encode()

def is_string(data):
    return isinstance(data, str)

def is_bytes(data):
    return isinstance(data, bytes)

I personally think that there isn't much gained by adding these two functions, but others may disagree (your post suggests you might). In otherwords, I would just write isinstance(data, str) wherever I see is_string. However, I think encodeable is sufficiently complicated to be a good stand-alone utility function.

I would also move:

s = str('spam')
r = r'eaggs'
b = b'slurm'
print('Before encoding')
print(s, r, b)
print(type(s), type(r), type(b), '\n')

print('After encoding')
s, r, b = encode(s), encode(r), encode(b)
print(encode(s), encode(r), encode(b))
print(type(s), type(r), type(b))

To a doctest.


Setting fields, with default values, before saving a row I would like to find out if there's a cleaner way to go about validating input before it goes into a function. What I'm doing seems like a lot of code, I'm sure there's a better way. I would also really appreciate some constructive criticism as my goal is to grow as a developer so anything you may see wrong with it or something you would've done better please mention it.

The code below does get the job done. I have tested it and it works, however I would like to improve its beauty and efficiency.

    Private Sub dgvproformas_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvproformas.CellContentClick

    Dim colname As String = ""

    colname = dgvproformas.Columns(e.ColumnIndex).Name

    Select Case colname

        Case "btnsave"

            Dim jobid As Integer = 0
            Dim proformano As String = ""
            Dim paymentreceiveddate As DateTime = Nothing
            Dim paymentreceived As Boolean = False
            Dim proformarequired As Boolean = False
            Dim proformaraised As Boolean = False

            jobid = dgvproformas.Item("job id", e.RowIndex).Value

            If Not IsDBNull(dgvproformas.Item("proformano", e.RowIndex).Value) Then
                proformano = dgvproformas.Item("proformano", e.RowIndex).Value
            End If

            If Not IsDBNull(dgvproformas.Item("proformapaymentreceived", e.RowIndex)) Then
                paymentreceived = dgvproformas.Item("proformapaymentreceived", e.RowIndex).Value
            End If

            If Not IsDBNull(dgvproformas.Item("proformarequired", e.RowIndex).Value) Then
                proformarequired = dgvproformas.Item("proformarequired", e.RowIndex).Value
            End If

            If Not IsDBNull(dgvproformas.Item("proformaraised", e.RowIndex).Value) Then
                proformaraised = dgvproformas.Item("proformaraised", e.RowIndex).Value
            End If

            If Not IsDBNull(dgvproformas.Item("proformapaymentreceiveddate", e.RowIndex).Value) Then
                paymentreceiveddate = dgvproformas.Item("proformapaymentreceiveddate", e.RowIndex).Value
            End If

            If MsgBox("Are you sure you'd like to save this record?", vbYesNo) = vbYes Then
                updateProforma(jobid, proformano, paymentreceived, proformaraised, proformarequired, paymentreceiveddate)
            End If

        Case Else

    End Select

End Sub

The problem with your code is that you keep repeating the same code over and over again.

If Not IsDBNull(dgvproformas.Item("columnName", e.RowIndex).Value) Then
  columnVar = dgvproformas.Item("columnName", e.RowIndex).Value
End If

What you need is function that does the same thing, so that you have code that looks more like this:

columnVar= fn(dgvproformas, "columnName", e.RowIndex)

Except we want to keep type safety so, a bit more like:

columnVar = fn(Of Integer)(dgvproformas, "columnName", e.RowIndex)

Personally, I like extension methods for something like this, and would create an extension method for it.  I would almost certainly name it GetValueOrDefault.

I believe you can eliminate the rowindex if you get the row, so combining the two...

Dim row = dgvproformas.Rows(e.RowIndex)
columnVar = row.GetValueOrDefault(Of Integer)("columnName")

Finally, I like meaningful names and dislike magic strings, so I like Nameof...

Dim row = dgvproformas.Rows(e.RowIndex)
columnName = row.GetValueOrDefault(Of Integer)(NameOf(columnName))


Social network queries for profiles, posts, and followers The code below is for a social networking system. The problem is that when there are many posts and many followers, the performance is slow.  Is something wrong with the queries and the script below?

public function __construct($dbo = NULL)
{
    parent::__construct($dbo);
}

public function count()
{
    $count = 0;

    $stmt = $this->db->prepare("SELECT * FROM profile_followers WHERE follower = (:followerId) ORDER BY create_at DESC");
    $stmt->bindParam(':followerId', $this->requestFrom, PDO::PARAM_INT);

    if ($stmt->execute()) {

        while ($row = $stmt->fetch()) {

            $stmt2 = $this->db->prepare("SELECT count(*) FROM posts WHERE fromUserId = (:fromUserId) AND removeAt = 0 ORDER BY createAt DESC");
            $stmt2->bindParam(':fromUserId', $row['follow_to'], PDO::PARAM_INT);
            $stmt2->execute();

            $count = $count + $stmt2->fetchColumn();
        }
    }

    return $count;
}

public function getMaxId()
{
    $stmt = $this->db->prepare("SELECT MAX(id) FROM posts");
    $stmt->execute();

    return $number_of_rows = $stmt->fetchColumn();
}

public function get($itemId = 0)
{
    if ($itemId == 0) {

        $itemId = $this->getMaxId();
        $itemId++;
    }

    $feed = array("error" => false,
                  "error_code" => ERROR_SUCCESS,
                  "itemId" => $itemId,
                  "items" => array());

    $stmt = $this->db->prepare("SELECT * FROM profile_followers WHERE follower = (:followerId) ORDER BY create_at DESC");
    $stmt->bindParam(':followerId', $this->requestFrom, PDO::PARAM_INT);

    if ($stmt->execute()) {

        $items = array();

        while ($row = $stmt->fetch()) {

            $stmt2 = $this->db->prepare("SELECT id FROM posts WHERE fromUserId = (:fromUserId) AND id < (:itemId) AND removeAt = 0 ORDER BY id DESC");
            $stmt2->bindParam(':fromUserId', $row['follow_to'], PDO::PARAM_INT);
            $stmt2->bindParam(':itemId', $itemId, PDO::PARAM_INT);
            $stmt2->execute();

            while ($row2 = $stmt2->fetch())  {

                $items[] = array("id" => $row2['id'], "itemId" => $row2['id']);
            }
        }

        $stmt3 = $this->db->prepare("SELECT id FROM posts WHERE fromUserId = (:fromUserId) AND id < (:itemId) AND removeAt = 0 ORDER BY id DESC");
        $stmt3->bindParam(':fromUserId', $this->requestFrom, PDO::PARAM_INT);
        $stmt3->bindParam(':itemId', $itemId, PDO::PARAM_INT);
        $stmt3->execute();

        while ($row3 = $stmt3->fetch())  {

            $items[] = array("id" => $row3['id'], "itemId" => $row3['id']);
        }

        $currentItem = 0;
        $maxItem = 20;

        if (count($items) != 0) {

            arsort($items);

            foreach ($items as $key => $value) {

                if ($currentItem < $maxItem) {

                    $currentItem++;

                    $item = new post($this->db);
                    $item->setRequestFrom($this->requestFrom);

                    $itemInfo = $item->info($value['itemId']);

                    array_push($feed['items'], $itemInfo);

                    $feed['itemId'] = $itemInfo['id'];

                    unset($itemInfo);
                    unset($item);
                }
            }
        }
    }

    return $feed;
}

public function setRequestFrom($requestFrom)
{
    $this->requestFrom = $requestFrom;
}

public function getRequestFrom()
{
    return $this->requestFrom;
}

}

I'm not surprised your script is slow. You are being really wasteful with resources.

You should rewrite your code to access the DB as few times as possible. Reading from the DB is an expensive operation, because it requires PHP to connect to DB, send execution instructions, wait for results, parse results and make them available to your script.  Notice for instance that in get(), your prepared $stmt2 and $stmt3 are identical. You're forcing your DB server to do the exact same work multiple times ($stmt2 is executed in a loop).  Why not call $this->db->prepare once and just bind different parameters to it before executing?  Better yet, can you compile all the fromUserIds you need and make the query once?  Start to think in this manner to reduce DB queries.
When you access the DB on every iteration of a loop, you're really paying a heavy price. For instance in count(), you execute a query to retrieve all the data for a particular follower, then for each result you execute another query to count the rows in posts table that belong to this follower. Look around SQL resources/forums to figure out how to do this in one query that will return followerId, count. Trust me, it can be done (hint: look into SQL Join operations).
Only select the data you need. For instance, instead of SELECT * FROM profile_followers in count(), if all you care about is the userId so you can match it against the same ID in posts table, then use SELECT userId.  The bigger your result set, the more memory your script will use.
NEVER sort if you don't need to. Sorting is really expensive. If you only care about the number of results (in count()), why are you sorting the results with ORDER BY x? Imagine if your boss asked you to sort all the words in this post alphabetically and report how many words there are.  I bet you won't bother to sort the words; you'll just count them and report the total.  Sorting is hard work.

Your intuition that your script is inefficient is right, so you have good instincts. Don't worry: once you're done optimizing you'll be amazed at the difference.


Diff Two Arrays - return the symmetric difference of the two arrays This is my challenge using JavaScript -> Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.

My code works, but I think that it can be better.

function diffArray(arr1, arr2) {
 var newArr = [];

  arr1.map(function(val){
   arr2.indexOf(val) < 0 ? newArr.push(val) : '';
  });

  arr2.map(function(val){
   arr1.indexOf(val) < 0 ? newArr.push(val) : '';
  });

  return newArr;
}

diffArray([1, 2, 3, 5, 6, 7], [1, 2, 3, 4, 5]);

What do you think?

As for performance: Array.indexOf in the worse case(element is not there), will have to check all values of the array to check if the value is in it. And doing this for all values of the second array, means O(n * m) where n is the arr1 size and m is the arr2 size. If n = m, we can consider that it takes O(n*n), which is quite expensive. You could improve this by sorting both arrays and doing a smarter check, but even that will have the cost of the sorting, which is O(n * log n) with a good implementation

Having said all that, what you really want is a structure to check if you have seen or not an element that can check it really quick. In javascript, we can use objets to do this. As its native code we don´t really know the complexity of access, but with testing a bit it is clear that it´s much better (in theory access should be O(1) or O(log n))

The pseudo code is like this:

var seen = {}
iterate all map1 values and mark is as seen
iterate all map2 values and unmark if already seen, mark if not
add all seen values to new array
return array

And here is a full fiddle:

function diffArray(arr1, arr2) {
  var newArr = [];

  arr1.map(function(val) {
    arr2.indexOf(val) < 0 ? newArr.push(val) : '';
  });

  arr2.map(function(val) {
    arr1.indexOf(val) < 0 ? newArr.push(val) : '';
  });

  return newArr;
}

function diffArray2(arr1, arr2) {
  seen = {}
  var newArr = []
  arr1.forEach(function(val) {
    seen[val] = 1 // we saw it on first array
  })
  arr2.forEach(function(val) {
    if (seen[val] == 1) { // we already saw it on the first one, unmark
      seen[val] = false
    } else if (seen.hasOwnProperty(seen[val]) == false) { // if we hadnt seen it earlier
      seen[val] = 2 // mark with a 2
    }
  })

  for (var val in seen) {
    if (seen[val]) { // if its a 1 or a 2, it was unique
      newArr.push(val)
    }
  }
  return newArr
}

var arr1 = []
var arr2 = []
var mx = 10000;
for (var i = 0; i < mx; i++) {
  arr1.push(i)
  arr2.push(i + Math.round(mx / 2))
}

console.time("diffArray with arrays and .index")
diffArray(arr1, arr2);
console.timeEnd("diffArray with arrays and .index")

console.time("diffArray with object")
diffArray2(arr1, arr2);
console.timeEnd("diffArray with object")


De-serializing and serializing objects to be sent over the network I am serializing and de-serializing a class object within the class which is then sent over the network like this:

class data
  public name as string
  public cmd as Commands
  public  message  as String

 Public Sub New(ByVal byteData As Byte())
        Try
            ' convert byte array to memory stream
            Using _ms As New MemoryStream(byteData)
                ' create new BinaryFormatter
                Dim _bf As New BinaryFormatter()
                ' set memory stream position to starting point
                _ms.Position = 0
                ' Deserializes a stream into an object graph and return as a object.
                dim oData as data =_bf.Deserialize(_ms)
                name = oData.name
                message = oData.Message
                cmd = oData.cmd
            End Using

        Catch ex As Exception
              Throw
        End Try

    End Sub

'Converts the Data structure into an array of bytes
    Public Function ToByte() As Byte()

        Dim bf As New BinaryFormatter()
        Try
            Using ms As New MemoryStream()
                bf.Serialize(ms, Me)
                Return ms.ToArray()
            End Using
        Catch ex As SerializationException
            Return Nothing
        Finally
            bf = Nothing
        End Try
    End Function
end class

Is this proper and efficient?

IMHO you are doing to much inside of the constructor (Sub New()). The constructor should be used to construct the object. It should be avoided that exceptions are thrown from inside of a constructor.

A better approach would be to add a Shared method which takes care of the deserializing and make the constructor private. This shared method would then return the fully constructed data object.

The exception handling in the constructor is senseless in its current state. You don't gain any advantage of using a Try..Catch because you are throwing the exception anyway. You can simply omit it.

Instead of calling ms.ToArray() in the ToByte() method you sould call ms.GetBuffer() which returns the content of the stream without creating a new byte array.

There is no need to set the Position property of the newly created MemoryStream. It is automatically set to the beginning. So skip _ms.Position = 0.

While we are at _ms, one shouldn't use underscore prefix unless it is a class level variable where it is accteptable.

  public name as string
  public cmd as Commands
  public  message  as String

These fields shouldn't be public avaible. For encapsulation you should use properties.

Comments should be used to explain why something is done in the way it is done. Let the code speak for itself about what is done by using meaningful and descriptive names for classes, methods and variables.
Comments like ' create new BinaryFormatter only add noise to the code which should be removed for readability.

In the ToByte() method the setting of bf = Nothing is not needed and therefor you should declare the BinaryFormatter as near to its usage as possible (inside the using).

The Catch ex As SerializationException would need a comment why you handle the exception like you do.

This 'Converts the Data structure into an array of bytes should be put inside a XML documentation block.

Dim oData as data

Please don't use hungarian notation like you are using it. By having intellisense you can easily hoover over the variable and see it is a class. There is no need to prefix it with o for object.

Naming a class data does not add any value. One should name a class in a way that it is obvious what purpose the class serves.

You also should be consistent at your naming style. Sometimese you are using an underscore prefix (like already stated) and sometimes you don't. If you have choosen a style you should stick to it.


C++ code to sort a list of elements This is a code uses mergesort algorithm to sort a list of elements.What are the possible improvements on the code?Also are there any unhealthy coding practice involved in this code?

#include<iostream>
#include<vector>
#include<random>
#include<chrono>
using namespace std;
using namespace std::chrono;
vector<int> merge(vector<int> a,vector<int> b){
    int i=0;
    int j=0;
    vector<int> result;
    while(i<a.size()&&j<b.size()){
        if(a[i]<b[j]){
            result.push_back(a[i]);
            i++;
        }
        else{
            result.push_back(b[j]);
            j++;
        }
    }
    while(i<a.size()){
        result.push_back(a[i]);
        i++;
    }
    while(j<b.size()){
        result.push_back(b[j]);
        j++;
    }
    return result;
}

vector<int> mergesort(vector<int> a,int low,int hi){
    vector<int> b,c,result;
    if(low==hi)
        return {a[hi]};
    b=mergesort(a,low,(low+hi)/2);
    c=mergesort(a,(hi+low)/2+1,hi);
    result=merge(b,c);
    return result;
}
int main(){

    std::random_device rd; // obtain a random number from hardware
    std::mt19937 eng(rd()); // seed the generator
    std::uniform_int_distribution<> distr(0,90); // define the range
    vector <int> num;
    for(int i=0;i<30;i++)
        num.push_back(distr(eng));
    vector<int> a=mergesort(num,0,num.size()-1);
    for(auto &i:a)
        cout<<i<<" ";
}

#include<iostream>
#include<vector>
#include<random>
#include<chrono>

Leave some space between the #includes and the rest of your code, that's easier to read. Besides, I really like <chrono> myself too, but you don't seem to use it afterwards.

using namespace std;
using namespace std::chrono;

using directives for a whole namespace is a bad idea. You risk conflicts between the names defined in std (and there's quite a lot of them) and those you define yourself. Safety is worth a few more keystrokes.

vector<int> merge(vector<int> a,vector<int> b){

That function signature means you're passing a and b by value, that is to say you copy the argument vectors. It might be the good move sometimes, but here it isn't, because you only read them. So const std::vector<int>& a, const std::vector<int>& b is better.

    int i=0;
    int j=0;

i, j, why not? but it doesn't scream what you'll be using those variables for.

    vector<int> result;
    while(i<a.size()&&j<b.size()){

I would rather use iterators in the first place (I mean, in the function's signature), because:

it avoids comparison issues (vector.size() is unsigned, whereas i and j are signed)
it makes it easier to write and use generic code
it allows you to merge sequences which are only a part of a container, or even inside the same container.

if(a[i]<b[j]){

There's a trick here: if a[i] == b[j] you'll insert b[j] first. It might be innocuous -it is for an int- but programmers expect that min(a, b) will return a if a == b. Since a sorting algorithm is a good candidate for abstraction (a vector of strings is sorted the same way as a vector of ints or floats), you should respect that rule.

        result.push_back(a[i]);
        i++;

Unless you need to keep track of the old value, use pre-incrementation (++i) since i++ creates and returns a temporary value.

        }
        else{
            result.push_back(b[j]);
            j++;
        }
    }
    while(i<a.size()){
        result.push_back(a[i]);
        i++;
    }
    while(j<b.size()){
        result.push_back(b[j]);
        j++;
    }

copy and paste is an anti-pattern. Standard algorithms will provide what you need in a more elegant way, especially if you use iterators: std::copy(current_a, a.end(), std::back_inserter(result));

    return result;
}

vector<int> mergesort(vector<int> a,int low,int hi){
    vector<int> b,c,result;
    if(low==hi)
        return {a[hi]};
    b=mergesort(a,low,(low+hi)/2);
    c=mergesort(a,(hi+low)/2+1,hi);
    result=merge(b,c);
    return result;
}

This part is all right, even if I believe you should try to reduce the place you need to merge-sort or at least the number of allocations.

int main(){

    std::random_device rd; // obtain a random number from hardware
    std::mt19937 eng(rd()); // seed the generator
    std::uniform_int_distribution<> distr(0,90); // define the range
    vector <int> num;
    for(int i=0;i<30;i++)
        num.push_back(distr(eng));
    vector<int> a=mergesort(num,0,num.size()-1);
    for(auto &i:a)

You generally don't take integers by reference (a reference is the size of or bigger than an int, and you don't take non-const references when you don't modify the variable, which you don't.

        cout<<i<<" ";
}


Formatting phone number without knowing locale I am trying to format supplied phone numbers for a web application.  Users in general will be supplying US-based phone numbers, but it is possible for some users to input a phone number from another country.

Here are my assumptions:

Default to US if the number of digits is 7 or 10 after stripping non-digits.  If not, just return the String
Use tested external
libraries where possible since speed isn't an utmost concern (the
service can be run in the background if it is really that slow).
Prefer an external library over a custom regex.

For the first assumption, I am thinking that if there is another country that has phone numbers with 7 or 10 digits, it's not the end of the world to have it formatted in US format.

Here's my code anyway, using Google's libphonenumber:

public static String formatPhoneNumber(String phoneNumber, Locale locale) throws NumberParseException {
    PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
    Phonenumber.PhoneNumber usNumber = phoneUtil.parse(phoneNumber, locale.getCountry());
    return phoneUtil.format(usNumber, PhoneNumberUtil.PhoneNumberFormat.NATIONAL);
}

public static String formatUSPhoneNumber(String phoneNumber) throws NumberParseException {

    //First strip out any non-digits
    phoneNumber = stripNonDigits(phoneNumber);

    phoneNumber = (phoneNumber == null) ? BaseConstants.EMPTY_STRING : phoneNumber;
    if ((phoneNumber.length() != 7) && (phoneNumber.length() != 10)) {
        return phoneNumber;
    }
    return formatPhoneNumber(phoneNumber, Locale.US);
}

I am adding this method to be comprehensive, but it's not directly needed for review (credit to SO):

public static String stripNonDigits(final CharSequence input){
    final StringBuilder sb = new StringBuilder(input.length());

    for(int i = 0; i < input.length(); i++){
        final char c = input.charAt(i);
        if(c > 47 && c < 58){
            sb.append(c);
        }
    }
    return sb.toString();
}

The associated JUnit tests:

@Test
public void testFormatPhoneNumber() throws NumberParseException {
  assertEquals(FormUtils.formatPhoneNumber("2122222222", Locale.US), "(212) 222-2222");
  assertEquals(FormUtils.formatPhoneNumber("2122222222", Locale.CANADA), "(212) 222-2222");
  assertEquals(FormUtils.formatPhoneNumber("(021)11111111", Locale.GERMANY), "0211 1111111");
}

@Test
public void testFormatUSPhoneNumber() throws NumberParseException {
  assertEquals(FormUtils.formatUSPhoneNumber("2122222222"), "(212) 222-2222");
  assertEquals(FormUtils.formatUSPhoneNumber("92122222222"), "92122222222");
  assertEquals(FormUtils.formatUSPhoneNumber("(212)2222222"), "(212) 222-2222");
  assertEquals(FormUtils.formatUSPhoneNumber("(212)222-2222"), "(212) 222-2222");
  assertEquals(FormUtils.formatUSPhoneNumber("(212) 222-2222"), "(212) 222-2222");
}

Is there a better way to do this?  Are there tests I should add?

Some improvements...

Variable re-assignment and null-check

You are re-assigning phoneNumber twice, and unfortunately I think you don't even need it at all.

First, it's generally not a nice idea to re-assign the method argument because careless mistakes may result in you inadvertently changing the instance referenced by it somewhere inside the method, when you're expecting the original input. Even if you don't explicitly final method parameters, it's simpler to always treat method arguments as an invariant so that you know what the method is processing on/with. Therefore, you should simply assign the output of stripNonDigits() to a new variable, and you can inline the new variable in the subsequent calls:

public static String formatPhoneNumber(String phoneNumber) throws NumberParseException {
    String strippedNumber = stripNonDigits(phoneNumber);
    return strippedNumber.length() != 7 && strippedNumber.length() != 10 ?
                strippedNumber : formatAsUSPhoneNumber(strippedNumber);
}

Now, you don't need a null-check (it's not in the right place anyways - it should be done at the start), and I renamed the main method as formatAsUSPhoneNumber(). I feel that formatUSPhoneNumber() is suggesting that it is formatting a US phone number into another representation.

stripNonDigits()

If stripNonDigits() should be used only by formatAsPhoneNumber(), consider making them private static. Ok, so even if you prefer not to use regex (fair point), how about Character.isDigit()? I feel that it's easier to read than the condition you have, short of the one-liner regex:

// replace all non-digits with an empty String
return input.toString().replaceAll("\\D+", "");


Finding repeating numbers in an array I want to search through an array of n numbers and find the numbers that are repeated. So far I have this code, which does the job, but I find it to be a rather cumbersome method, but I can't seem to find another method of doing it.

class Checknumber{
    int [] numbers = new int [5];
    Scanner inn = new Scanner(System.in);
    boolean b = true;
    int temp = -1;

    void sjekk(){
        System.out.println("Write five numbers");
        for(int i = 0; i < numbers.length; i++){
        numbers [i] = inn.nextInt();
    }

    //sjekker om det er like tall i arrayen
    System.out.print("\nNumbers that are repeated: ");
    for(int i = 0; i < numbers.length; i++){

        if(!b){
            System.out.print(temp + " ");
        }

        b = true;
        temp = numbers[i];
        for(int j = 0; j < numbers.length; j++){
            if(i != j && temp == numbers[j] && numbers[j] != -2){
                b = false;
                numbers[j] = -2;
            }
        }
    }

}

Others have given alternate solutions.  However, since this is Code Review, I'll offer a critique instead, because I think you will learn more from that than by just seeing the answer.

Interfaces

Checknumber is too vague.  I suggest DuplicateNumberDetector.
In your interfaces (class and method names), pick either English or Norwegian and stick with it.  For your comments, use whatever language works for you.
sjekk() (meaning "check") is actually responsible for receiving input rather than performing the checking.  How misleading!

Variables

b is very poorly named.  I suggest unique instead.
temp is somewhat poorly named.  I suggest num instead.
Only older dialects of C require you to declare all variables at the top.  Java lets you declare variables near the point of first use.  You should take advantage of that.  int temp should be declared inside the for (i) loop, since it is never used outside the loop.
You might try to pull the declaration of b inside the for (i) loop too.  But then you will realize that b refers to the uniqueness of the previous numbers[i].  That reveals a bug: what if the last two numbers are identical (numbers[3] == numbers[4], but numbers[2] != numbers[3])?  You haven't handled the termination case correctly.  Hint: Move your print statement.  The lesson to be learned here is that declaring temporary variables far from the point of use is almost as evil and dangerous as using global variables.

Logic

You are using -2 as a special value to indicate that an array element has already been detected as a duplicate. That's bad because your code will fail if -2 happens to be one of the inputs.
Overwriting the input array is a surprising side effect.  That's as unforgivable as sending your computer to a repair shop to install a video card and getting it back with the hard drive reformatted.  If you really need to overwrite the input, state so clearly in a comment.  You should be able to find a solution to this problem that does not require overwriting.
Your inner loop has j going from 0 to the end of the array.  That means you are handling every pair twice.  You should probably be able to start from i + 1 instead, to reduce your processing in half.  Handling each pair only once should simplify your logic as well.

Efficiency

You have two for loops, each iterating over the entire array.  If the array has n elements, then the run time for your algorithm is O(n2).  (Even with the inner-loop optimization mentioned in the previous point, it would still be O(n2).)  For a small homework problem like this, that is perfectly acceptable, because simplicity is the main goal.  If you wanted to handle very large arrays, though, it would be more efficient to sort the input first or use a HashMap.

Separation of concerns

Your input, processing, and output code are all intertwined.  Get into the habit of separating them.  Your code will be more reusable and easier to understand.

.

public class DuplicateNumberDetector {
    int[] promptInputs(int numberOfInputs) { ... }

    // If the order doesn't matter, use Set<Integer> instead
    List<Integer> findDuplicates(int[] numbers) { ... }

    void printDuplicates(List<Integer> dups) { ... }

    public static void main(String[] args) {
        printDuplicates(findDuplicates(promptInputs(5)));
    }
}


DRY for rendering same header table for different content I'm trying to make the following code DRY. The code outputs a table that shows violations. If there is any violation.status = resolved they go in separate table for resolved items. Since the header and columns of the table are the same, I believe I should be able to make this DRY using a For loop. However, I'm not sure that's possible in Django templates.

There's three relevant context variables:

violation_list which is a query set of all violations
not_resolved_violations which is (1) excluding status = resolved
resolved_violations which is (1) filtered on status = resolved

{% if violation_list %}

{% if not_resolved_violations %}

Open Violations

        #
        IDENTIFIER

{% for violation in not_resolved_violations %}

        {{ forloop.counter }}

            {{ violation.identifier }}

{% endfor %}

{% endif %}

{% if resolved_violations %}

Resolved Violations

        #
        IDENTIFIER

{% for violation in resolved_violations %}

        {{ forloop.counter }}

            <a href='#'

{% endfor %}

{% endif %}

{% else %}

This project doesn't have any violations associated it with it.

{% endif %}

You might try building a slightly more complex datastructure to be passed in.  If you built a list like:

violations = [ ("Resolved", resolved_violations),
               ("Open", unresolved_violations) ]

Then you could write a template like:

{% for vtype, vlist in violations %}
    {% if vlist %}

{{ vtype }} Violations

        #
        IDENTIFIER

        {% for violation in vlist %}

        {{ forloop.counter }}

            {{ violation.identifier }}

        {% endfor %}

    {% endif %}
{% endfor %}


Singleton class with custom initializer In a Swift project, I have a class should be used as a singleton:

  class NearFieldManager : NSObject{
  static let shared = NearFieldManager()
  var dataToTransfer:Any!
 }

This class helps me communicate between several nearby devices and the dataToTransfer is some information each device is advertising about itself.
What makes me wondering about this class is that each time I call it goes like this:

let manager = NearFieldManager.shared
shared.dataToTransfer = "some data"

First, I am creating a reference to the manager and line after it I set some value on its property. How can I improve this design?

Assuming the dataToTransfer is always the same for a specific device, you can create this data in init()

class NearFieldManager {
    static let shared = NearFieldManager()
    private let dataToTransfer: Any

    private init() { //private to forbid instantiation
        self.dataToTransfer = methodToCreateDeviceData()
    }
}


Number of Chocolates to Gluttonize in Clojure I’ve been dabbling in Clojure by solving programming puzzles. This particular puzzle is from HackerRank, with the objective of figuring out how much chocolate one could eat given three parameters:

The cost of a piece of chocolate
How much money you have
The candy shop owner will give you a free chocolate for x number of wrappers

In the code below, those three numbers are passed to total-chocolates-consumed which returns the answer.

(ns hr.clojure.algorithms.implementation.implementation.chocolate-feast)

(defn int-division
  [numerator denominator]
  (->>
    (/ numerator denominator)
    int))

(defn number-to-purchase
  [totalToSpend costPerChocolate]
  (int-division
    totalToSpend
    costPerChocolate))

(defn number-of-freebies
  [totalWrappers wrappersPerFreebie]
  [(int-division
    totalWrappers
    wrappersPerFreebie)
   (int
     (mod
       totalWrappers
       wrappersPerFreebie))])

(defn total-chocolates-consumed
  [totalToSpend
   costPerChocolate
   wrappersPerFreebie]
   (let [purchasedChocolates (number-to-purchase totalToSpend costPerChocolate)
         freebies (first (number-of-freebies purchasedChocolates wrappersPerFreebie))
         totalChocolates [purchasedChocolates freebies]
         startRemainder (second (number-of-freebies purchasedChocolates wrappersPerFreebie))]
         (loop
           [chocs totalChocolates
            remainder startRemainder]
           (cond
            (> wrappersPerFreebie (+ remainder (last chocs)))
               (reduce + chocs)
             :else
              (recur
                (conj chocs (first (number-of-freebies (+ (last chocs) remainder) wrappersPerFreebie)))
                (second (number-of-freebies (+ (last chocs) remainder) wrappersPerFreebie)))))))

I've written tests for this code here:

(ns hr.clojure.algorithms.implementation.implementation.chocolate-feast.spec)

(load-file "YOUR-PATH-TO-FILE")
(use 'hr.clojure.algorithms.implementation.implementation.chocolate-feast)
(use 'clojure.test)

(deftest chocolate-feast
  (testing "number-to-purchase"
    (is (= 0 (number-to-purchase 2 10)))
    (is (= 2 (number-to-purchase 10 4)))
    (is (= 666 (number-to-purchase 1000 1.5)))
    (is (= 3 (number-to-purchase 6 2)))
    (is (= 5291 (number-to-purchase 10000 1.89))))
  (testing "number-of-freebies"
    (is (= [0 1] (number-of-freebies 1 2)))
    (is (= [100 0] (number-of-freebies 100 1)))
    (is (= [2 0] (number-of-freebies 3 1.5)))
    (is (= [1 1] (number-of-freebies 3 2))))
  (testing "total-chocolates-consumed"
    (is (= 6 (total-chocolates-consumed 10 2 5)))
    (is (= 3 (total-chocolates-consumed 12 4 4)))
    (is (= 5 (total-chocolates-consumed 6 2 2)))
    (is (= 899 (total-chocolates-consumed 43203 60 5)))))

(deftest math-library
  (testing "int-division"
    (is (= 0 (int-division 7 12)))
    (is (= 2 (int-division 12 6)))
    (is (= 2 (int-division 12 5)))))

(run-tests)

General Questions

Is this how tests are written in Clojure?
Is the code readable? Can you tell what I was thinking?

How idiomatic is my code?

Should I use camel case for parameter names?
Should I hyphenate my function names?
Is this “waterfall” sort of formatting typical?

What is a good way to communicate what a function does?

For instance, number-of-freebies returns a vector of [chocolates earned with wrappers, wrappers leftover]. Could I return a type that actually indicates what those values are to the consumer of that function?

How do I refactor total-chocolates-consumed to be less complex?

There is some redundant code in there for figuring the number of freebies, could I pull that out into a local value within the loop?
Should I be using a loop or some higher-order function?

General Questions

Yes. Your tests are fine.
I found the code hard to follow without the requirements. To some degree, that's to be expected. Even once I read the requirements, there were things that I found hard to follow. More on that later.

How idiomatic is my code?

Never use camel case for your clojure-defined symbols.
You should always use lower-cased, hyphenated names in Clojure.
Your formatting was fine, except the let statement. It should be formatted like so:

(let [my-thing :a
      other-thing :b]
  (code-that-does-stuff ...))

The clojure style guide should tell you everything you need to know about styling your code.

What is a good way to communicate what a function does?

This is a complex question. My first piece of advice is to accurately name the function. number-of-freebies implies a number, but you are returning a vector. So a more appropriate name might be division-tuple or, better, quotient-remainder-tuple.

Regarding return types, the options you have, in order of increasing ceremony, are:

Return a tuple.
Return a map whose keys denote the return values.
Define a type or record.

For this example, I think a tuple is fine. If I thought the return value might need to expand in the future, I'd consider using a map. I generally use records and types when:

I'm designing a large(er) system (i.e. doing design work as opposed to implementing functions)
I want to reify a complex type
I want type dispatch

So, for something like this, I'd consider types to be a little overkill. Your tastes may vary.

How do I refactor total-chocolates-consumed to be less complex?

I implemented a solution in preparing your feedback, and the most straightforward method I could come up with on the fly was indeed recursive. Though, I will say this tends to be the kind of problem that you realize can be solved with map/reduce after a night or two of sleep.

There are two things you can do to make total-chocolates-consumed less complex:

Use destructuring:

(let [[freebies startRemainder] (number-of-freebies purchasedChocolates wrappersPerFreebie)]
  ...)

Use more let statements. Specifically inside the loop-recur.

I have a version of total-chocolates-consumed that does those things if you want to see it. I thought you might like to take a stab at it before you see what I did.

Other Notes

When I moved from Java to Clojure, I tended to like very small functions (e.g. number-to-purchase or int-division).
Over time, I've found it's a) more idiomatic and b) easier to read if you start with a rather large function and break it up as needed to increase understanding.
My reasoning for this preference is that Clojure already gives you really good, simple building blocks.
This allows you to define the simple functions that directly enrich your domain without worrying as much about length.
If I want added documentation, I will let a variable with a good name.

On the topic of int-division, I'm pretty sure you can solve this problem with just quot and rem. Wasn't sure you were aware of those functions.
Feel free to let me know if I'm mistaken there.

Lastly, in my solution, I tried to focus first on calculating the purchased chocolates, then on calculating the freebies,
as opposed to creating a seq of all chocolates, then summing them up at the end.  This separation of concerns allows you to structure the program
intent clearly at the topmost level. It has the added benefit of making the recursive part of the program a bit more straightforward.

Update

Per OP's request, here is my solution:

(defn calculate-freebies [purchased-chocolates wrappers-per-freebie]
  (loop [remaining-wrappers purchased-chocolates
         free-chocolates 0]
    (if (< remaining-wrappers wrappers-per-freebie)
      free-chocolates
      (let [new-chocolates (quot remaining-wrappers
                                 wrappers-per-freebie)]
        (recur
          (+ (rem remaining-wrappers
                  wrappers-per-freebie)
             new-chocolates)
          (+ free-chocolates new-chocolates))))))

(defn calculate-chocos [bobs-money cost-of-chocolate wrappers-per-freebie]
  (let [purchased-chocolates (quot bobs-money
                                   cost-of-chocolate)
        freebies (calculate-freebies purchased-chocolates
                                     wrappers-per-freebie)]
    (+ purchased-chocolates freebies)))

Note that I did go ahead and pull out calculate-freebies into a separate defn. I did that because a) it's a standalone concept and b) it makes calculate-chocos easier to read. If it weren't a standalone concept, I would have likely defined it in the let of calculate-chocos itself.


Asking Windows for real-time priority This code snippet is about asking Windows for the highest possible execution priority. Basically, we have to ask for real-time priority class for the entire process, after which each thread has to ask for real-time thread priorities. However, since Windows Vista, whatever is the program that needs the real-time priority, it must be asked to be run in administrator privilege level.

The demonstration program I provide simply loops for 7 seconds. During that period, your system should be frozen (try pressing Caps Lock; should not switch the Caps Lock light). Also, if you put on some audio, the sound card will repeat its contents of the sound buffer over and over again.

rtprio.h:

#pragma once
#include <Windows.h>

BOOL RealTimePriorityClass()
{
    return SetPriorityClass(GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
}

BOOL RealTimeThreadPriority()
{
    return SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
}

main.cpp:

#include <windows.h>
#include "rtprio.h"

static const DWORD dwInterval = 7000; // millseconds.

DWORD WINAPI ThreadProc(LPVOID lpParams);

int WINAPI WinMain(HINSTANCE hInst,
    HINSTANCE hPrev,
    LPSTR lpCmdLine,
    int nShowCmd)
{
    DWORD       i;
    DWORD       dwInitTicks;
    DWORD       dwCores;
    SYSTEM_INFO sysInfo;

    GetSystemInfo(&sysInfo);
    dwCores = sysInfo.dwNumberOfProcessors;

    // Ask real-time priority class for the entire process.
    RealTimePriorityClass();

    for (i = 0; i < dwCores - 1; i++)
    {
        CreateThread(NULL,
                     0,
                     ThreadProc,
                     NULL,
                     0,
                     NULL);
    }

    RealTimeThreadPriority();

    dwInitTicks = GetTickCount();

    while (GetTickCount() - dwInitTicks < dwInterval);

    return 0;
}

DWORD WINAPI ThreadProc(LPVOID lpParams)
{
    // Ask for real-time priority for this thread.
    RealTimeThreadPriority();

    // Freeze the system for dwInterval milliseconds.
    while (TRUE) {}

    return 0;
}

Works as intended.
But I get a thread priority of 15 rather than the expected 31 for a REALTIME_PRIORITY_CLASS?
See SetThreadPriority.

It seems that the THREAD_PRIORITY_TIME_CRITICAL is defined to THREAD_BASE_PRIORITY_LOWRT - 1, which could be further elevated to 31 if needed.


Optimize jQuery image gallery for production I can't seem to find a very simple light weight image gallery, so I decided to build my own. I'm not an expert in jQuery/JavaScript, so I was hoping some suggestions could be made to make this production material. I have a working example on jsfiddle.

data-rel will end up being the full size image URL while img src will become the thumb url. I'd like to limit full size images from having to be all loaded at once on page render.

jsFiddle

test

prev

next

JavaScript

$("#gallery img").first().load(function(){
    activeImg($(this));
});

$("#gallery img").on('click, mouseover', function(){
    activeImg($(this));
});

$('#button-next').click(function(){
    var isLast = $('#gallery img.active').is(':last-child');

    if (isLast) {
        activeImg($('#gallery img').first());
    } else {
        activeImg($('#gallery img.active').next());
    }
});

$('#button-previous').click(function(){
    var isFirst = $('#gallery img.active').is(':first-child');

    if (isFirst) {
        activeImg($('#gallery img').last());
    } else {
        activeImg($('#gallery img.active').prev());
    }
});

var activeImg = function($img) {
    $('.active').removeClass('active');

    var imgUrl = $img.addClass('active').data('rel');
    $("#area").html("");
};

CSS

#button-previous {float:left;}
#button-next {float:right;}
img{border:1px solid #000}
img.active{border-color:red}

It's quite fine, but it can be simplified a little bit.
In the HTML, the img elements all have the same style value.
It would be better to remove the style attribute from all the img,
and define in the stylesheet instead:

#gallery img {
    max-width:150px;
    max-height:50px;
}


Using a list-matrix to supply indices to N-dimensional array I am working on a partial differential equations project where some N-dimensional objects are required. I got stuck in padding one N-dim object with a copy of each of its dimensions. Here is the function:

padreplicate <- function(a, padSize) {
    # A: is a N-dimensional array
    # padSize: is a vector that defines the padding
    # Pad an array by replicating values.
    numDims <- length(padSize)
    idx <- vector("list", numDims)
    for (k in 1:numDims) {
        M <-  dim(a)[k]       # 32
        onesVector <-  matrix(1, 1, padSize[k])
        idx[[k]] <- c(onesVector, 1:M, M * onesVector)
    }
    do.call( `[`, c(list(a), idx))
}

The first argument is the N-dim object; it could be a matrix, a 3D array or higher dimensional array.

An example for a 2D object or matrix would be:

# pad a matrix 4x3 with c(1,1)
set.seed(123456)
mx = matrix(sample.int(9, size = 9*100, replace = TRUE), nrow = 4, ncol = 3)
mx
  #       [,1] [,2] [,3]
  # [1,]    8    4    9
  # [2,]    7    2    2
  # [3,]    4    5    8
  # [4,]    4    1    6
padreplicate(mx, c(1,1))

The padded matrix looks like this:

      [,1] [,2] [,3] [,4] [,5]
[1,]    8    8    4    9    9
[2,]    8    8    4    9    9
[3,]    7    7    2    2    2
[4,]    4    4    5    8    8
[5,]    4    4    1    6    6
[6,]    4    4    1    6    6

For a 3-D array the input array and the padded array.

ar = array(sample.int(9, size = 9*100, replace = TRUE), dim = c(3, 3, 1))
ar
padreplicate(ar, c(1,1,1))

# input 3x3x1 array
, , 1

     [,1] [,2] [,3]
[1,]    3    4    6
[2,]    7    2    9
[3,]    3    4    8

   # padded 5x5x3 array
, , 1

     [,1] [,2] [,3] [,4] [,5]
[1,]    3    3    4    6    6
[2,]    3    3    4    6    6
[3,]    7    7    2    9    9
[4,]    3    3    4    8    8
[5,]    3    3    4    8    8

, , 2

     [,1] [,2] [,3] [,4] [,5]
[1,]    3    3    4    6    6
[2,]    3    3    4    6    6
[3,]    7    7    2    9    9
[4,]    3    3    4    8    8
[5,]    3    3    4    8    8

, , 3

     [,1] [,2] [,3] [,4] [,5]
[1,]    3    3    4    6    6
[2,]    3    3    4    6    6
[3,]    7    7    2    9    9
[4,]    3    3    4    8    8
[5,]    3    3    4    8    8

These are all correct results from my unit tests.

My question is this: "is there a better way of doing this N-dim padding operation in R or a package that address N-dimensional arrays?

Using your 2D example, doing mx[c(1, 1, 2, 3, 4, 4), c(1, 1, 2, 3, 3)] is the obvious solution, both elegant and fast. So your way of generalizing the use of [ via do.call to handle any number of dimensions is what I would consider the optimal approach. The rewrite below won't make the code faster but maybe a little more simple and robust. The main improvement is the computation of the idx using Map rather than a for loop. And I added a number of stopifnot checks to verify all the assumptions you are making regarding your inputs.

padreplicate <- function(a, padSize) {
   stopifnot(is.array(a),
             is.vector(padSize),
             is.numeric(padSize),
             length(padSize) == length(dim(a)),
             padSize >= 0L)
   idx <- Map(function(p, n) c(rep(1L, p), seq(n), rep(n, p)),
              padSize, dim(a))
   do.call( `[`, c(list(a), idx))
}


Providing const- and non-const overloads of a strstr() implementation In a question about reimplementing strstr(), I posted an answer.  I pointed out a need for const- and non-const versions of the function, and provided Implementation A below, which received criticism about the ugliness of the const_cast.  Therefore, I've written two more implementations (B and C).

Implementation A: const version that chains to a non-const version

char *strstr(char *input, const char *find) {
    do {
        const char *p, *q;
        for (p = input, q = find; *q != '\0' && *p == *q; p++, q++) {
        }
        if (*q == '\0') {
            return input;
        }
    } while (*(input++) != '\0');
    return NULL;
}

const char *strstr(const char *input, const char *find) {
    return strstr(const_cast<char *>(input), find);
}

Implementation B: template

template <typename T>
T *strstr(T *input, const T *find) {
    do {
        const T *p, *q;
        for (p = input, q = find; *q != '\0' && *p == *q; p++, q++) {
        }
        if (*q == '\0') {
            return input;
        }
    } while (*(input++) != '\0');
    return NULL;
}

Implementation C: template with char_traits

template <typename T>
struct char_traits {
    typedef T type;
    typedef const T const_type;
};

template <typename T>
static typename char_traits<T>::type *strstr(
        typename char_traits<T>::type *input,
        typename char_traits<T>::const_type *find) {
    do {
        typename char_traits<T>::const_type *p, *q;
        for (p = input, q = find; *q != '\0' && *p == *q; p++, q++) {
        }
        if (*q == '\0') {
            return input;
        }
    } while (*(input++) != '\0');
    return NULL;
}

// Explicit instantiation doesn't help with overloading?
// http://stackoverflow.com/a/8061522/1157100
//
// template char *strstr<char>(char *input, const char *find);
// template char *strstr<const char>(char *input, const char *find);

// So it seems that chaining is still necessary?
const char *strstr(const char *input, const char *find) {
    return strstr<const char>(input, find);
}

char *strstr(char *input, const char *find) {
    return strstr<char>(input, find);
}

I suspect that I may have done something stupid with (C), since I'm still chaining the calls.  Is there a way to provide an overloaded strstr() just using template instantiation?

Of the three approaches, which is best, and why?

I don't like casting away const on a const object.
This opens you up to the possibility of maintenance errors.

const char *strstr(const char *input, const char *find)
{
    return strstr(const_cast<char *>(input), find);
}

Here you are assuming that the other version of strstr() will not attempt to mangle the input. This may be fair to assume in the original version, but what if somebody makes a mistake while updating to use a better algorithm. The compiler will not detect the problem and you are left with UB.

I would just do it the other way around:

char const* strstr(char const* input, char const* find)
{
   do {
        char const* p;
        char const* q;
        for (p = input, q = find; *q != '\0' && *p == *q; p++, q++) {
        }
        if (*q == '\0') {
            return input;
        }
    } while (*(input++) != '\0');
    return NULL;
}

char* strstr(char* input, char const* find)
{
    return const_cast<char*>(strstr(const_cast<char const*>(input), find));
}

OK. So we need to add another cast. But in this version we protect ourselves from errors. If there is an error in the algorithm (were input is modified) then the compiler will now be able to detect it.

The const_cast<> to remove const(ness) is in a safe place returning the pointer to its original state (after there is const_cast<> to add const (needed so we can differentiate the two functions).

Personally I would take it a step further (so we can remove one of the const_casts). By making the strstr() just wrapper functions around the function that does the work.

char const* strstrDo(char const* input, char const* find)
{
   do {
        char const* p;
        char const* q;
        for (p = input, q = find; *q != '\0' && *p == *q; p++, q++) {
        }
        if (*q == '\0') {
            return input;
        }
    } while (*(input++) != '\0');
    return NULL;
}

// Interface for backwards compatibility with old C code
// that does not handle const correctness well.
char* strstr(char* input, char const* find)
{
    // It is safe to cast away the const(ness) here.
    // The result of `strstrDo()` is a location inside
    // `input` (which we already know is non const) or
    // it is NULL (where the type is less relevant).

    return const_cast<char*>(strstrDo(input, find));
}

// Correct interface.
char const* strstr(char const* input, char const* find)
{
   return strstrDo(input, find);
}

Don't like Implementation B: template because it has the same problems in that errors (in modification input are not detected by the compiler (potentially)).

Same for Implementation C: template with char_traits. But that goes way over the top. I don't actually see the need for the traits on such a simple function.


Custom session handler I'm new to PDO and haven't been coding in a while. Is the following custom session handler industry-acceptable?

class Session {
    protected $sdb;

    function __construct() {
        session_set_save_handler(array($this, '_open'), array($this, '_close'), array($this, '_read'), array($this, '_write'), array($this, '_destroy'), array($this, '_clean'));
        register_shutdown_function('session_write_close');
    }

    function _open() {
        $this->sdb['conn'] = new PDO('mysql:host=' . DBHOST . ';dbname=' . DBNAME . ';charset=utf8', DBUSER, DBPASS);
        $this->sdb['conn']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        return TRUE;
    }

    function _close() {
        $this->sdb['conn'] = NULL;

        return TRUE;
    }

    function _read($sid) {
        try {
            $this->sdb['read']['query'] = $this->sdb['conn']->prepare('SELECT data FROM sessions WHERE sid = :sid LIMIT 1')) {
            $this->sdb['read']['query']->bindParam(':sid', $sid, PDO::PARAM_STR);
            $this->sdb['read']['query']->execute();
            $this->sdb['read']['result'] = $this->sdb['read']['query']->fetch(PDO::FETCH_ASSOC);
        }
        catch( PDOException $exception ) {
            var_export($exception);

            return FALSE;
        }

        $this->sdb['read']['query']->closeCursor();

        return $this->sdb['read']['result']['data'];
    }

    function _write($sid, $data) {
        try {
            $this->sdb['write']['query'] = $this->sdb['conn']->prepare('REPLACE INTO sessions VALUES (:sid, :time, :data)');

            $this->sdb['write']['query']->bindParam(':sid', $sid, PDO::PARAM_STR);
            $this->sdb['write']['query']->bindParam(':time', date('Y-m-d H:i:s'));
            $this->sdb['write']['query']->bindParam(':data', $data, PDO::PARAM_STR);
            $this->sdb['write']['query']->execute();
        }
        catch( PDOException $exception ) {
            var_export($exception);

            return FALSE;
        }

        $this->sdb['write']['query']->closeCursor();

        return TRUE;
    }

    function _destroy($sid) {
        try {
            $this->sdb['destroy']['query'] = $this->sdb['conn']->prepare('DELETE FROM sessions WHERE id = :sid');

            $this->sdb['destroy']['query']->bindParam(':sid', $sid, PDO::PARAM_STR);
            $this->sdb['destroy']['query']->execute();
        }
        catch( PDOException $exception ) {
            var_export($exception);

            return FALSE;
        }

        $this->sdb['destroy']['query']->closeCursor();

        return TRUE;
    }

    function _clean() {
        try {
            $this->sdb['clean']['query'] = $this->sdb['conn']->prepare('DELETE FROM sessions WHERE access < :stale');

            $this->sdb['clean']['query']->bindParam(':stale', date("Y-m-d H:i:s", strtotime("-30 minutes")));
            $this->sdb['clean']['query']->execute();
        }
        catch( PDOException $exception ) {
            var_export($exception);

            return FALSE;
        }

        $this->sdb['clean']['query']->closeCursor();

        return TRUE;
    }
}

It would be better to implement SessionHandlerInterface.
Your code is tightly coupled, move session_set_save_handler out from constructor to some bootstrap file. Also this class shouldn't create db connection, it is better to pass it as a constructor parameter:

$conn = new PDO('mysql:host=' . DBHOST . ';dbname=' . DBNAME . ';charset=utf8', DBUSER, DBPASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$handler = new MySessionHandler($conn);
session_set_save_handler($handler, true);

Constructor for the session handler:

class Session implements \SessionHandlerInterface
{
    protected $conn;

    public function __construct(\PDO $conn)
    {
        $this->conn = $conn;
    }

    // ....
}

This gives you more freedom, in case you decide to extend PDO you can pass it there. Also you don't need to create separate connection for application and session.
Implementing Interface ensures that you fulfill all requirements.

What I find odd is that you put every query to handler property, they should be local variables, you create them on every method call anyway.


Query optimization PHP for string concatination I have an entity RegistrationForm which has a OneToMany-relationship with  SurveyAnswer.

An answer can either have a collection of FormOptions (when the answer is of type MULTIPLE_CHOICE) or a content represented by a string (type TEXT-FIELD, TEXTAREA etc.).

Below is a function inside the RegistrationForm-entity that tries to obtain a string-based representation of the answer's content.

public function getAnswerByColumnId($columnId) {
    foreach ($this->surveyAnswers as $answer) {
        if ($answer->getFormQuestion()->getId() == $columnId) {
            $formOptions = $answer->getFormOptions();
            if (count($formOptions) > 0) {
                $content = '';
                foreach ($formOptions as $key => $option) {
                    if ($key == 0) {
                        $content .= $option->getName();
                    } else {
                        $content .= ' , ' . $option->getName();
                    }
                }
                return $content;
            } else {
                return $answer->getContent();
            }
        }
    }
    return 'No column match, contact admin';
}

I am creating a table out of the registration forms. Each registration form has a few answers that are of a multiple-choice type.

The result is that the foreach ($formOptions as $key => $option) {...-section is pumping the amount of queries up from 200 to 2500.  How can I improve this?

For now, one solution is to concatenate the options into a string while the answer is persisted. This is part of my FormToArrayTransformer:

switch ($_question->getFormField()->getType()) {
    case FormField::CHOICE:
        $content = '';

        foreach($answer as $_key=>$option) {
            $surveyAnswer->addFormOption($option);
            if ($_key == 0) {
                $content .= $option->getName();
            } else {
                $content .= ', ' . $option->getName();
            }
        }

        $surveyAnswer->setContent($content);
        break;

Note that now both the FormOption entities and their string representation is stored. When viewing you don't have to iterate over the options anymore but simply calling answer.getContent() will do. This saved me 2300 queries in a table for 200 forms.

I am still unsure why this is so.


Find all distinct palindromic sub-strings for a given string I was solving a question where I had to find all possible unique palindromes of size greater than 1 for a string.

I was able to come up with the solution shown below. If I am not mistaken it is an \$O(n^2)\$ solution. I'd like feedback on improving the code and if my understanding of its time complexity is correct.

def check_palin(word):
    for i in xrange(len(word)/2):
        if word[i] != word[-1*(i+1)]:
            return False
    return True

def all_palindromes(string):

    left,right=0,len(string)
    j=right
    results=[]

    while left < right-1:
        temp = string[left:j] #Time complexity O(k)
        j-=1

        if check_palin(temp):
            results.append(temp)

        if j<left+2:
            left+=1
            j=right

    return list(set(results))

print all_palindromes("racecarenterelephantmalayalam")

Output:

['aceca', 'layal', 'cec', 'alayala', 'racecar', 'ele', 'ere', 'aya', 'malayalam', 'ala']

Time complexity

Yes, your solution has a O(n^2) time complexity. As the output is n^2 where the input is n, achieving a better time complexity is impossible.

Look at the following code + output:

for i in range(1, 51):
    string = "a" * i
    permutations = list(palindrome_substrings("a"*i))
    print(len(string), len(permutations), len(permutations) /  float(len(string)))

(1, 1, 1.0)
(2, 3, 1.5)
(3, 6, 2.0)
(4, 10, 2.5)
(5, 15, 3.0)
(6, 21, 3.5)
(7, 28, 4.0)
(8, 36, 4.5)
(9, 45, 5.0)
(10, 55, 5.5)
(11, 66, 6.0)
(12, 78, 6.5)
(13, 91, 7.0)
(14, 105, 7.5)
(15, 120, 8.0)
(16, 136, 8.5)
(17, 153, 9.0)
(18, 171, 9.5)
(19, 190, 10.0)
(20, 210, 10.5)
(21, 231, 11.0)
(22, 253, 11.5)
(23, 276, 12.0)
(24, 300, 12.5)
(25, 325, 13.0)
(26, 351, 13.5)
(27, 378, 14.0)
(28, 406, 14.5)
(29, 435, 15.0)
(30, 465, 15.5)
(31, 496, 16.0)
(32, 528, 16.5)
(33, 561, 17.0)
(34, 595, 17.5)
(35, 630, 18.0)
(36, 666, 18.5)
(37, 703, 19.0)
(38, 741, 19.5)
(39, 780, 20.0)
(40, 820, 20.5)
(41, 861, 21.0)
(42, 903, 21.5)
(43, 946, 22.0)
(44, 990, 22.5)
(45, 1035, 23.0)
(46, 1081, 23.5)
(47, 1128, 24.0)
(48, 1176, 24.5)
(49, 1225, 25.0)
(50, 1275, 25.5)

As you can see, not only the output size grows with the input, the ratio between output size and input size grows too. This means that the time complexity is quadratic.

Generators and all

As far as the code is concerned, it is not Pythonic, it looks like C as it does not make use of generator expressions and built-ins like any or all.

def is_palindrome(word):
    return all(word[i] == word[-1*(i+1)] for i in xrange(len(word)//2))

I kept your way of looping and multiplying by -1, but now the code reads at a higher level: all the i-th chars must equal the (-1 * (i+1)) - th  chars. And the efficiency is the same as all short-circuites (aborts the computation as soon as it finds a counterexample.)

Separation of concerns

Getting the substrings of a string is interesting in its own right.Why am I forced to get only the palindrome ones? Make substrings a separate function.

Going one level deeper

You can actually nest the loops in the generator expression, getting the substrings of a string may be written as:

def substrings(string):
    return (string[i:j+1] for i in range(len(string)) for j in range(i, len(string)))

Or in a more imperative-looking (but equivalent) manner:

def substrings(string):
    for i in range(len(string)):
        for j in range(i, len(string))):
            yield string[i:j+1]

The final function

And getting the palindrome substrings is now very easy:

def palindrome_substrings(string):
    return (i for i in substrings(string) if is_palindrome(i))

Side note about names

Use long descriptive names, over cryptic abbreviations:

check_palin -> check_palindrome or following the is_ convention (boolean-returning functions should have a name starting with is_) is_palindrome
all_palindromes: What does all stand for? It stands for substrings so just write it like  that: -> palindrome_substrings

Bug fix

a is a palindrome, in general all single char strings are palindromes, so your code not returning them means it has a bug. My code rightly returns single char palindromes.


A program that checks for Palindromness Yes, I made it up.

This program checks if an entered string is a palindrome or not by assigning a char variable the characters in the inserted word in reverse order. The program then takes the variable and appends it to a  StringBuilder to be able to compare the original word and the finalized reversed version.

package Palindrome;

import java.util.Scanner;

public class palindrome {

static String word;
StringBuilder reversedWord = new StringBuilder();

public palindrome() {
    char reversedChar;

    for (int i = 1; i < word.length() + 1; i++) {
        reversedChar = word.charAt(word.length() - i);
        reversedWord.append(reversedChar);
    }
}

public void checkPalindrome() {
    if(word.equalsIgnoreCase(reversedWord.toString())) {
        System.out.println("You got a Palindrome!");
    }else{
        System.out.println("That's not a Palindrome...");
    }
}

public static void main(String[] args) {
    System.out.print("Enter a word to check Palindromness: ");
    Scanner scan = new Scanner(System.in);
    word = scan.next();
    scan.close();
    new palindrome();
    new palindrome().checkPalindrome();
    }
}

notes:

Your coding style seems good. There is some inconsistent indentation,
but i am guessing that is a question formatting problem.
Having a static variable word means that palindrome is not
threadsafe, and is confusing to call. either pass word to the
palindrome constructor, or make checkPalindrome() a static method
that takes a string.
checkPalindrome() outputs it's result to standard output. What if
you wanted to make your palindrome checker graphical?. have
checkPalindrome() return a boolean indicating whether word is a
palindrome or not. This concept of seperating model and output code
is extremly important.
Instead of wasting time and memory copy over the string backwards then
checking for equality, you can compare pairs of characters starting at
both ends of the string.
When you reverse the string, you can write a for loop that goes
backwards:

for (int i = word.length() - 1; i >= 0; --i) {
    reversedChar = word.charAt(i);
    reversedWord.append(reversedChar);
}

example:

public boolean checkPalindrome(String word) {
    for (int i = 0; i < word.length() / 2; ++i) {
        if (Character.toLowerCase(word.charAt(i)) !=
                Character.toLowerCase(word.charAt(word.length()-i-1))) {
            return false;
        }
        return true;
}


Should methods be inside classes? in Ruby I have coded more in Python but I am learning Ruby now. So I am trying to write a solution to create a family_tree and add and get relationships. The code below is of the file that contains the main function which is called from the command line. The below code works and solves the problem but I have written methods without classes. In python it is acceptable. Is is acceptable in ruby? Even though the code works is this how it is written in Ruby? Or does this need refactoring? If yes then please tell how?
#main_file.rb
require_relative 'family'
require_relative 'family_tree'
include FamilyTree
require_relative 'constants'
require_relative 'errors'

def is_valid_input(command)
  #User input Validation
  commands = command.split(' ')
  return false unless (commands && INPUT_FUNCTION_MAPPER.key?(commands[0]))
  return false if (commands[0] == "ADD_CHILD" && commands.length != 4)
  return true
end

def create_family_tree(family_tree)
  #Initializing the family
  family_name = family_tree[:name]
  members = family_tree[:members]

  family = Family.new(family_name)
  members.each do |name, gender, mother_name|
    family.add_member(name, gender, mother_name)
  end
  family
end

def execute_command(command, family)
  result = nil
  unless is_valid_input(command)
    raise InvalidParametersError, "Command is not valid"
  end
  command = command.split(" ")
  if command[0] == "ADD_CHILD"
    mother, name, gender = command[1..]
    result = family.add_member(name, gender, mother)
  end
  result
end

def main_method
  if ARGV.length != 1
    raise InvalidParametersError, "Please provide an input file"
  end
  input_file = ARGV[0]
  unless File.file?(input_file)
    raise InvalidParametersError, "Input file does not exist"
  end

  family = create_family_tree(FAMILYTREE)
  File.readlines(input_file).each do |line|
    line = line.strip
    puts execute_command(line, family)
  end
end

main_method()

This is executed as below:
ruby main_file.rb input.txt

This "global function" style works for small scripts but isn't reusable.
A more practical problem with it is if you want to have state that is shared between functions, you don't have anywhere to store it (well, you could use global variables ($var), but that's prone to conflicts).
For a more encapsulated design, create a class that does the work and move the methods into the class. See for example definition and usage.


Python program that checks connections based on URLLIB response The main function tries to create a urllib connection, and if it fails/succeeds the label changes accordingly. However, I'm looking for ways to improve this code.

Some elements I'm already aware of:

The use of place really isn't ideal, I'm aware
Importing Urllib twice, but if I didn't do it like this the except: wasnt working correctly
Use of global

import urllib
import urllib.request as url
from tkinter import *

master = Tk()
master.geometry("280x36")
master.resizable(False, False)
master.config(bg="#4b4b4b")
master.overrideredirect(True)

master.wm_geometry("-0-40")
master.wm_attributes("-topmost", 1)

connectStatus = Label(bg="#e67e22", fg="#fff", width=29, height=1, text="Pending", font="Bahnscrift 10")
connectStatus.place(x=10,y=8)

closeButton = Button(width=2, bg="#706f6f", fg="#fff", borderwidth=0, text="x", command=master.destroy)
closeButton.place(x=253, y=8)

def displayCheck():
    colorFlash = "#38f789" if callbackAttempt == 1 else "#ff6656"
    connectStatus.config(bg=colorFlash)
    master.after(10, runRefresh)

def runRefresh():
    attemptConnect()
    master.after(2000, displayCheck)

def attemptConnect():
    global callbackAttempt

    try:
        callbackAttempt = 1
        callback = url.urlopen("https://stackoverflow.com", timeout=1)
        connectStatus.config(text="Connection Established", font="Bahnscrift 10", bg="#2ecc71")
        callback.close()

    except urllib.error.URLError:
        connectStatus.config(text="No Connection", bg="#e74c3c", font="Bahnscrift 10")
        callbackAttempt = 0

master.after(5, runRefresh)
master.mainloop()

It's a neat idea, I like it! There is however a couple different things that could be done differently, while retaining the original idea.

Syntax

Have a look at PEP-8, it's a universal style guide for Python, it will give you an idea of how to style your code. As an example: functions, methods and variables should be snake_case, not mixedCase or CamelCase. While the use of the latter won't raise a syntax error, using PEP-8 is preferred.

Try to avoid wildcard imports (importing contents of entire libraries), as it will pollute your namespace. In the point below I suggest a library that's not part of the standard library, which should be separated from standard library imports, by one line.

import tkinter as tk

import requests

attemptConnect function

I would consider switching to a higher level web request solution, the requests library. It comes with all the features we need out of the box and additionally it provides an extremely handy Session object. Basically, it will use the underlying TCP connection making the subsequent requests faster. We will send a HEAD request, so the content won't be requested.

At first I thought the global variable is a counter of some sort, but a closer look made me realise it acts as a boolean variable. Why not make it one? This change will also have an effect in your ternary: "#38f789" if request_successful else "#ff6656".

I've taken the liberty to start changing function and variable names to follow PEP-8.

session = requests.Session()
...
def verify_url_status():
    global request_successful
    try:
        session.head('https://stackoverflow.com/')
        request_successful = True
        status_label.config(text="Connection Established", bg="#2ecc71", font="Bahnscrift 10")
    except requests.exceptions.ConnectionError:
        status_label.config(text="No Connection", bg="#e74c3c", font="Bahnscrift 10")
        request_successful = False

Classes

I have never worked much with tkinter, but this problem begs for the use of a class, encapsulating your code with it would make it more modular and would solve the need for a global variable. I will refer you to this tutorial, as it will be more comprehensive than what I know. If you haven't touched object oriented programming in Python yet, I'd recommend reading up on it as well. Below is the basic idea.

import tkinter as tk

import requests

class URLStatus:

    def __init__(self):
        self.session = requests.Session()
        self.request_successful = None
        self.master = tk.Tk()
        ...
        self.status_label = tk.Label(bg="#e67e22", fg="#fff", width=29, height=1, text="Pending", font="Bahnscrift 10")
        self.status_label.place(x=10,y=8)

    def verify_url_status(self):
        try:
            self.session.head('https://stackoverflow.com/')
            self.request_successful = True
            self.status_label.config(text="Connection Established", bg="#2ecc71", font="Bahnscrift 10")
        except requests.exceptions.ConnectionError:
            self.status_label.config(text="No Connection", bg="#e74c3c", font="Bahnscrift 10")
            self.request_successful = False