texts:
I have decided to make small ObjectPool class for internal use. What do you think about it ?

template<class T>
class ObjectPool
{
public:
    inline T& getObject();
    inline void releaseObject(T& obj);
private:
    std::stack<std::reference_wrapper<T>> mFree;
    std::vector<T> mPool;
};

template<class T>
void ObjectPool<T>::releaseObject(T& obj)
{
    mFree.push(obj);
}

template<class T>
T& ObjectPool<T>::getObject()
{
    if (mFree.size()) {
        T& num = mFree.top();
        mFree.pop();
        return num;
    } else {
        mPool.emplace_back();
        return mPool.back();
    }
}

I also want to make all function and data static. Is that considered a bad practice?


texts:
I have to create a 5x5 box using the images, and my first solution was to create 25 variables and print them, which is very inefficient. How can I optimize this? This utilizes cocos2d-x.

auto cudrado0 = Sprite::create("images.png");
cudrado0->setPosition(Vec2(200, 200));
cudrado0->setScale(0.5);
this->addChild(cudrado0, 0);

auto cudrado1 = Sprite::create("images.png");
cudrado1->setPosition(Vec2(200, 275));
cudrado1->setScale(0.5);
this->addChild(cudrado1, 0);

 auto cudrado2 = Sprite::create("images.png");
cudrado2->setPosition(Vec2(200, 350));
cudrado2->setScale(0.5);
this->addChild(cudrado2, 0);

auto cudrado3 = Sprite::create("images.png");
cudrado3->setPosition(Vec2(200, 425));
cudrado3->setScale(0.5);
this->addChild(cudrado3, 0);

auto cudrado4 = Sprite::create("images.png");
cudrado4->setPosition(Vec2(200, 500));
cudrado4->setScale(0.5);
this->addChild(cudrado4, 0);

 auto cudrado5 = Sprite::create("images.png");
cudrado5->setPosition(Vec2(275, 200));
cudrado5->setScale(0.5);
this->addChild(cudrado5, 0);

auto cudrado6 = Sprite::create("images.png");
cudrado6->setPosition(Vec2(350, 200));
cudrado6->setScale(0.5);
this->addChild(cudrado6, 0);

 auto cudrado7 = Sprite::create("images.png");
cudrado7->setPosition(Vec2(425, 200));
cudrado7->setScale(0.5);
this->addChild(cudrado7, 0);

auto cudrado8 = Sprite::create("images.png");
cudrado8->setPosition(Vec2(500, 200));
cudrado8->setScale(0.5);
this->addChild(cudrado8, 0);

  auto cudrado9 = Sprite::create("images.png");
cudrado9->setPosition(Vec2(275, 275));
cudrado9->setScale(0.5);
this->addChild(cudrado9, 0);

 auto cudrado10 = Sprite::create("images.png");
cudrado10->setPosition(Vec2(350, 275));
cudrado10->setScale(0.5);
this->addChild(cudrado10, 0);

auto cudrado11 = Sprite::create("images.png");
cudrado11->setPosition(Vec2(425, 275));
cudrado11->setScale(0.5);
this->addChild(cudrado11, 0);

auto cudrado12 = Sprite::create("images.png");
cudrado12->setPosition(Vec2(500, 275));
cudrado12->setScale(0.5);
this->addChild(cudrado12, 0);

auto cudrado13 = Sprite::create("images.png");
cudrado13->setPosition(Vec2(275, 350));
cudrado13->setScale(0.5);
this->addChild(cudrado13, 0);

auto cudrado14 = Sprite::create("images.png");
cudrado14->setPosition(Vec2(350, 350));
cudrado14->setScale(0.5);
this->addChild(cudrado14, 0);

auto cudrado15 = Sprite::create("images.png");
cudrado15->setPosition(Vec2(425, 350));
cudrado15->setScale(0.5);
this->addChild(cudrado15, 0);

auto cudrado16 = Sprite::create("images.png");
cudrado16->setPosition(Vec2(500, 350));
cudrado16->setScale(0.5);
this->addChild(cudrado16, 0);

auto cudrado17 = Sprite::create("images.png");
cudrado17->setPosition(Vec2(275, 425));
cudrado17->setScale(0.5);
this->addChild(cudrado17, 0);

auto cudrado18 = Sprite::create("images.png");
cudrado18->setPosition(Vec2(350, 425));
cudrado18->setScale(0.5);
this->addChild(cudrado18, 0);

auto cudrado19 = Sprite::create("images.png");
cudrado19->setPosition(Vec2(425, 425));
cudrado19->setScale(0.5);
this->addChild(cudrado19, 0);

auto cudrado20 = Sprite::create("images.png");
cudrado20->setPosition(Vec2(500, 425));
cudrado20->setScale(0.5);
this->addChild(cudrado20, 0);

auto cudrado21 = Sprite::create("images.png");
cudrado21->setPosition(Vec2(275, 500));
cudrado21->setScale(0.5);
this->addChild(cudrado21, 0);

auto cudrado22 = Sprite::create("images.png");
cudrado22->setPosition(Vec2(350, 500));
cudrado22->setScale(0.5);
this->addChild(cudrado22, 0);

auto cudrado23 = Sprite::create("images.png");
cudrado23->setPosition(Vec2(425, 500));
cudrado23->setScale(0.5);
this->addChild(cudrado23, 0);

auto cudrado24 = Sprite::create("images.png");
cudrado24->setPosition(Vec2(500, 500));
cudrado24->setScale(0.5);
this->addChild(cudrado24, 0);


texts:
I'm a first year college student, Computer Science major. This is my crack at the FizzBuzz interview question in Java. What kind of improvements could I make?

//Prints numbers 1 - 100, 25 values per line.
//Numbers that are multiples of 3 are replaced with Fizz
//Numbers that are mulitples of 5 are replaced with Buzz
//Numbers that are multiples of both 3 and 5 are replaced with FizzBuzz

public class FizzBuzz {

    public static void main(String[] args) {

        String fizz = "Fizz";
        String buzz = "Buzz";
        String fizzBuzz = "FizzBuzz";

        //Loop from 1 through 100
        for (int i = 1; i <= 100; i++) {

            if (i % 3 == 0 && i % 5 == 0) {          //Checks for numbers that are both multiples of 5 and 3
                if (i % 25 != 0) {                   //Control flow allows 25 values printer per line
                    System.out.printf("%4.8s ", fizzBuzz);
                }
                else {
                    System.out.printf("%4.8s\n ", fizzBuzz);
                    System.out.println();
                }

            }

            else if (i % 3 == 0) {                   //Checks for numbers that are multiples of 3
                if (i % 25 != 0) {                   //Control flow allows 25 values printer per line
                    System.out.printf("%4.8s ", fizz);
                }
                else {
                    System.out.printf("%4.8s\n ", fizz);
                    System.out.println();
                }

            }

            else if (i % 5 == 0) {                   //Checks for numbers that are multiples of 5
                if (i % 25 != 0) {                   //Control flow allows 25 values printer per line
                    System.out.printf("%4.8s ", buzz);
                }
                else {
                    System.out.printf("%4.8s\n ", buzz);
                    System.out.println();
                }

            }

            else {                                   //Prints numbers that are not multiples of 3 or 5
                if (i % 25 != 0) {                   //Control flow allows 25 values printer per line
                    System.out.print(i + " ");
                }
                else {
                    System.out.println(i + " ");
                    System.out.println();
                }
            }
        }
    }
}


texts: Formatting milliseconds as days, hours, minutes, and seconds

texts:
This is a function which aims to convert an amount of milliseconds to a more human-interpretable Day(s) Hour(s) Minute(s) Second(s) format:

function dhms(t) {
    d = Math.floor(t / (1000 * 60 * 60 * 24)),
    h = Math.floor((t % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
    m = Math.floor((t % (1000 * 60 * 60)) / (1000 * 60)),
    s = Math.floor((t % (1000 * 60)) / 1000);
    return d + 'Day(s) ' + h + 'Hour(s) ' + m + 'Minute(s) ' + s + 'Second(s)'
}

So for getting the variables values I have for now something quite verbose:

d = Math.floor(t / (1000 * 60 * 60 * 24)),
h = Math.floor((t % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
m = Math.floor((t % (1000 * 60 * 60)) / (1000 * 60)),
s = Math.floor((t % (1000 * 60)) / 1000);

Is it the way to go? Or should I go with:

d = Math.floor(t / 86400000),
h = Math.floor(t % 86400000 / 3600000),
m = Math.floor(t % 3600000 / 60000),
s = Math.floor(t % 60000 / 1000);

Or even with:

d = Math.floor(t / 864e5),
h = Math.floor(t % 864e5 / 36e5),
m = Math.floor(t % 36e5 / 6e4),
s = Math.floor(t % 6e4 / 1e3);

Or another way? How is it recommended to assign time values?


texts: Project Euler 10: find the sum of all the primes below two million

texts:
This is question #10 from Project Euler:

  The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million.

I just started programming and read that a Sieve of Eratosthenes is the fastest way to find primes however this code is taking forever to run. How can I make this go faster?

end = False
all = list(range(2, 2000000))
delnum = 2
while all.index(delnum)+1 <= len(all) and end == False:
    for x in all:
        if x % delnum == 0 and delnum != x:
            all.remove(x)
    if all.index(delnum)+1 == len(all):
        end = True
    if all.index(delnum)+1 <= len(all) and end == False:
        delnum = all[all.index(delnum) + 1]
print(sum(all))


texts: Remove duplicates from an unsorted Linked List in Ruby

texts:
Currently I'm going over the cracking the coding interview. I'm in the Linked List 2.1 question which is as follow:

  Remove Duplicates, write code to remove duplicates from an unsorted
  Linked List. How would you solve the problem if a temporary buffer is
  not allowed?

I used a Hash, which breaks the temporary buffer not allowed conditioned. Not sure how one can go about solving this without using an extra data structure. The above is the method I used.

# CTCI-2.1: Write code to remove duplicates from an unsorted LinkedList
  def remove_duplicates
    node = @head
    h = Hash.new(0)
    return false unless node.next
    h[@head.data] += 1
    while (node = node.next)
      h[node.data] += 1
      if h[node.data] > 1
        previous_node = find_previous(node.data)
        previous_node.next = previous_node.next.next
      end
    end
  end

This is a \$O(n)\$. How can this be improved? How one will go about solving this without using an additional data structure(Temporary buffer?) Here is the rest of the Linked List:
require 'pry'

class Node
  attr_accessor :next
  attr_reader :data

  def initialize(data)
    @data = data
    @next = nil
  end

  def to_s
    "Node with value: #{data}"
  end
end

class LinkedList
  def initialize
    @head = nil
  end

  def append(value)
    if @head
      find_tale.next = Node.new(value)
    else
      @head = Node.new(value)
    end
  end

  def find_tale
    node = @head

    return node if !node.next
    return node if !node.next while (node = node.next)
  end

  def find(value)
    node = @head

    return false if !node.next
    return node if node.data == value

    while (node = node.next)
      return node if node.data == value
    end
  end

  def append_after(target, value)
    node = find(target)
    return unless node

    old_next = node.next
    node.next = Node.new(value)
    node.next.next = old_next
  end

  def find_previous(value)
    node = @head

    return false if !node.next
    return node if node.next.data == value

    while(node = node.next)
      return node if node.next.data == value
    end
  end

  def delete(value)
    if @head.data == value
      @head = @head.next
    end

    node = find_previous(value)
    node.next = node.next.next
  end

  def display
    node = @head

    puts node
    while (node = node.next)
      puts node
    end
  end

  # CTCI-2.1: Write code to remove duplicates from an unsorted LinkedList
  def remove_duplicates
    node = @head
    h = Hash.new(0)
    return false unless node.next
    h[@head.data] += 1
    while (node = node.next)
      h[node.data] += 1
      if h[node.data] > 1
        previous_node = find_previous(node.data)
        previous_node.next = previous_node.next.next
      end
    end
  end
end

Here is the test I used:

# TEST
list = LinkedList.new

list.append('A')
list.append('B')
list.append('A')
list.append('A')
list.append('C')
list.append('D')

puts "Display the list"

list.display

list.remove_duplicates
puts 'Answer should be A B C D'
list.display


texts: Customer search using LINQ followed by conditional filtering of results

texts:
I have a search function in my class which checks various class property values for null or certain values and queries the database based on those properties. This how my function looks like now:

 public object searchCustomerList()
    {
        object partner = null;
        try
        {
            using (var rep = new OrderEntities())
            {
                var results = (from par in rep.Partners
                               join term in rep.CustomerTerms on par.TERMID equals term.TERMID
                               select new
                               {
                                   par.ID,
                                   par.COMPANY,
                                   par.CONTACT,
                                   par.PRICECAT,
                                   par.STATE,
                                   par.TERMID,
                                   par.PHONE,
                                   term.TERMDESC
                               });
                if (customerDetails.priceCategory != Prog.allObjectsIndex) {
                    results = results.Where(c => c.PRICECAT == customerDetails.priceCategory);
                }
                if (customerDetails.termID != Prog.allObjectsIndex) {
                    results = results.Where(c => c.TERMID == customerDetails.termID);
                }
                if (customerDetails.customerState != Prog.allObjectsIndex)
                {
                    results = results.Where(p => p.STATE == customerDetails.customerState);
                }
                if (!string.IsNullOrWhiteSpace(customerDetails.companyName))
                {
                    results = results.Where(p => p.COMPANY.Contains(customerDetails.companyName));
                }
                if (!string.IsNullOrWhiteSpace(customerDetails.contactPerson))
                {
                    results = results.Where(p => p.CONTACT.Contains(customerDetails.contactPerson));
                }
                partner = results.AsEnumerable()                                                                        // Execute method call in Linq-to-Objects
                            .Select(x => new                                                                            // The rest of the query is evaluated in memory
                            {
                                x.ID,
                                x.COMPANY,
                                x.CONTACT,
                                PRICECAT=Prog.getPriceCategory()[(int) x.PRICECAT],
                                STATE = Prog.getStatus()[(int)x.STATE],
                                x.TERMDESC
                            }).OrderBy(x => x.COMPANY).ToList();

            }
        }
        catch (Exception ex)
        {
            saveError("Failed to extract customer information. Error Description:" + ex.Message);
        }
        return partner;
    }

From the little that I know about LINQ, this function is ineffective as it first searches the database and then searches subsets of the result.

Is there a more effective way to re-write this function?


texts: Splitting a text file into paragraphs and words

texts:
I'm iterating through a number of text files, trying to locate all carriage-returns, and individually save the text between carriage-returns. I get the index numbers of all carriage-returns, but I haven't got the slightest about saving the text.

Basically I want to save every string between two carriage-returns into an individual variable. The next step is to save all the words within a string as an individual hash.

Here is my code so far (edited based on the help by Tin Man and Screenmutt) to get every single paragraph of a file into an array:

# script start

# outputfile
output_text = File.open("output.txt", 'w')

# directory with files
Dir.chdir("nkamp")

#count lines
lines = File.readlines("first.txt")
line_count = lines.size
text = lines.join
paragraph_count = text.split("\.\r").length
puts "#{paragraph_count} paragraphs."

#array of paragraphs
paragraphs = Array.new
contents = []
File.foreach("first.txt", "\.\r") do |paragraph|
  puts paragraph.chomp
  puts '-' * 40
  contents << paragraph.chomp
  paragraphs << paragraph.chomp
end

puts paragraphs[10]

This code gives me an array with all the paragraphs. I am using ".\r" instead of "\n\n" because the texts are copied from PDF files, and have lost the normal page layout structures.

The next step is to save an array of the words in a paragraph into the array instead of simply a string of text:

words_in_each_paragraph = Array.new

File.foreach("Ann Reg Sci (2).txt", "\.\r") do |paragraph|
    word_hash = {}
    paragraph.split(/\W+/).each_with_object(word_hash) { |w, h|
        h[w] = []
    }
    words_in_each_paragraph << word_hash
end

puts words_in_each_paragraph[8]

Which gives the following output:

{""=>[], "The"=>[], "above"=>[], "contributions"=>[], "highlight"=>[], "the"=>[], "importance"=>[], "of"=>[], "sophisticated"=>[], "modeling"=>[], "work"=>[], "for"=>[], "a"=>[], "better"=>[], "understanding"=>[], "complexity"=>[], "entrepreneurial"=>[], "space"=>[], "economy"=>[]}

Now the next step is loop through every file, and create a dynamic hash that gives me

a. a number for the article. b. a number for the paragraph. c. the list of words as seen above.

For this I need to learn how to dynamically create hashes. This is where it goes wrong:

lines = File.readlines("test.txt")
line_count = lines.size
text = lines.join
paragraph_count = text.split("\.\r").length
puts "#{paragraph_count} paragraphs."

testArray = Array.new(paragraph_count.to_i, Hash.new)
for i in 0...paragraph_count.to_i do
    testArray[i] = Hash.new
    puts "testArray #{i} has been made"
end
words_in_each_paragraph = Array.new

File.foreach("test.txt", "\.\r") do |paragraph|
    word_hash = {}
    paragraph.split(/\W+/).each_with_object(word_hash) { |w, h|
        h[w] = []
    }
    words_in_each_paragraph << word_hash
    testArray[i][:value] = word_hash
    puts testArray[i] # IT WORKS HERE #
end

puts testArray[1] # AND IT DOESN'T WORK HERE #


texts: Merging bin-data via a bin count threshold

texts:
When performing a chi-squared test, one takes the square of the differences of the expected counts per bin and observed counts per bin, and divides these per-bin differences by the expected counts per bin, as seen in the formula below.

However, I've heard that it is good practice to modify the bins such that the observed counts are above a threshold (typically 5, sometimes less) as a large number of bin counts below such a threshold can result in a bad fit (assuming minimized chi-squared). If the observed bin count is less than this threshold, then the bin is merged with the next bin. Assuming a distribution (such as a Gaussian) with a central peak, the next bin would be the next-right bin (i to i+1 bin) when the bins are left of the central peak while the next bin would be the next-left bin (i to i-1 bin) when the bins are to the right of the central peak.

I've created an algorithm that I believe works and covers all-edge cases (assuming a single central peak). I was wondering how it could be improved in terms of speed/efficiency. I also feel like I am duplicating code using similar approaches in two while-loops; can this be averted?

import numpy as np

## CONVENIENCE FUNCTIONS
get_midpoints = lambda edges : (edges[1:] + edges[:-1])/2
verify = lambda string, data : print("\n .. {} {}:\n{}\n".format(len(data), string, data))

## SAMPLE DATA
bin_edges = np.linspace(0, 40, 9)
bin_mids = get_midpoints(bin_edges)
bin_counts = np.array([2, 12, 21, 31, 18, 9, 3, 1])

## DESIRED OUTPUT (VIA THRESHOLD=5)
upd_edges = np.array([0, 10, 15, 20, 25, 40])
upd_mids = get_midpoints(upd_edges)
upd_counts = np.array([14, 21, 31, 18, 13])

## ALGORITHM TO MODIFY BINS
def modify_bins(edges, counts, threshold=None):
    """
    This function returns the bin edges, bin midpoints, and bin counts
    with the option of including a count threshold.

    edges       :   type <array>
    counts      :   type <array>
    threshold   :   type <int> greater than 0 or None
    """
    if threshold is None:
        return edges, mids, counts
    else:
        ## INITIALIZE
        loc_peak = np.argmax(counts)
        left_edges = [edges[0]]
        left_counts = []
        right_edges = []
        right_counts = []

        ## CONSOLIDATE BINS LEFT OF PEAK
        idx = 0
        while idx <= loc_peak:
            count_tmp = counts[idx]
            edge_tmp = edges[idx+1]
            while count_tmp < threshold:
                idx += 1
                count_tmp += counts[idx]
                edge_tmp = edges[idx+1]
            left_edges.append(edge_tmp)
            left_counts.append(count_tmp)
            idx += 1

        ## CONSOLIDATE BINS RIGHT OF PEAK
        idx = len(counts) - 1
        while idx > loc_peak:
            count_tmp = counts[idx]
            edge_tmp = edges[idx+1]
            while count_tmp < threshold:
                idx -= 1
                count_tmp += counts[idx]
                edge_tmp = edges[idx+1]
            right_edges.append(edge_tmp)
            right_counts.append(count_tmp)
            idx -= 1

        ## GROUP LEFT & RIGHT DATA
        right_edges[0] = edges[-1]
        mod_edges = np.array(left_edges + right_edges[::-1])
        mod_counts = np.array(left_counts + right_counts[::-1])
        mod_mids = get_midpoints(mod_edges)
        return mod_edges, mod_mids, mod_counts

# mod_edges, mod_mids, mod_counts = modify_bins(bin_edges, bin_counts, threshold=None)
mod_edges, mod_mids, mod_counts = modify_bins(bin_edges, bin_counts, threshold=5)

## VERIFY
verify("ORIGINAL EDGES", bin_edges)
verify("ORIGINAL MIDPOINTS", bin_mids)
verify("ORIGINAL COUNTS", bin_counts)
print("-----------------------------")
verify("DESIRED EDGES", upd_edges)
verify("DESIRED MIDPOINTS", upd_mids)
verify("DESIRED COUNTS", upd_counts)
print("-----------------------------")
verify("MODIFIED EDGES", mod_edges)
verify("MODIFIED MIDPOINTS", mod_mids)
verify("MODIFIED COUNTS", mod_counts)


texts: Locating the largest Collatz Sequence with memoization

texts:
Inspired by this question I wrote a memoized form of the collatz sequence calculator.

The idea was to cache the sequence lengths for as many sequences as possible, from 0 to some value. I managed to (on my PC) get that value up to 1427500000, which is a large number.

I ran this particular calculator and it eventually crashed (because Java long isn't big enough) as follows:

New best: 4890328815 at 1131 chains in 342.77514018s.
Value from chain 8528817511 at length 205 is negative: -7694391518238975012
At 10000000000 of 10000000000 (100%) in 712.666022051s
Best: 4890328815 at 1131 chains.
Largest number in any chain: 7168235036980384402

That is expected and intended. I just wanted to see what the largest value it could get to was.

Feel free to comment on anything related to the code.

public class CR_150878 {
    public static void main(String[] args) {
        long maxTestValue = 10000000000l;

        int maxLength = 0;
        long maxNumber = 0;
        int chainSize = 0;

        int maxSequenceMapLength = 1427500000;
        int[] sequenceLengthMap = new int[maxSequenceMapLength];

        long largestNumberAnyChain = 0;

        long startTime = System.nanoTime();
        for (long i = 2; i < maxTestValue; i++) {
            chainSize = 0;
            long currentNumber = i;

            while (currentNumber != 1) {
                if (currentNumber > 1 && currentNumber < maxSequenceMapLength && sequenceLengthMap[(int)currentNumber] != 0) {
                    chainSize += sequenceLengthMap[(int)currentNumber];
                    currentNumber = 1;
                } else {
                    if (currentNumber % 2 == 0) {
                        currentNumber = currentNumber / 2;
                    } else {
                        currentNumber = 3 * currentNumber + 1;
                    }
                    chainSize++;

                    if (currentNumber < 0) {
                        System.out.println("Value from chain " + i + " at length " + chainSize + " is negative: " + currentNumber);
                        currentNumber = 1;
                        i = maxTestValue;
                    }
                }

                if (currentNumber > largestNumberAnyChain) {
                    largestNumberAnyChain = currentNumber;
                }
            }

            if (i > 1 && i < maxSequenceMapLength) {
                sequenceLengthMap[(int)i] = chainSize;
            }

            if (chainSize > maxLength) {
                maxLength = chainSize;
                maxNumber = i;
                System.out.println("New best: " + maxNumber + " at " + maxLength + " chains in " + ((double)(System.nanoTime() - startTime) / 1000000000) + "s.");
            }

            if (i % (maxTestValue / 100) == 0) {
                System.out.println("At " + i + " of " + maxTestValue + " (" + (i / (maxTestValue / 100)) + "%) in " + ((double)(System.nanoTime() - startTime) / 1000000000) + "s");
            }
        }

        System.out.println("Best: " + maxNumber + " at " + maxLength + " chains.");
        System.out.println("Largest number in any chain: " + largestNumberAnyChain);
        System.out.println("Took: " + ((double)(System.nanoTime() - startTime) / 1000000000) + " seconds.");
    }
}

The class name is intentional, it was a code rewrite to that particular Code Review question.

It's a slightly optimized algorithm, instead of doing \$3n+1\$ I did \$(3n+1)/2\$ to avoid having to do all sorts of math to the next number, but then I lost the accuracy of the "Largest number in any chain" and whatnot values, so I undid it. (Believe it or not a whole minute was trimmed off execution time.)

This also solves the Project Euler 14 challenge in 0.13s.


texts: Simple: Need help refactoring this awkward looking method

texts:
I need help refactoring this method. It is way too long.

  def report_total(feed_event, advisor)
    count = 0
    advisor.activity_feed_events.each do |lead|
      if lead == SignupFeedEvent
        count += 1
      else
        if lead.is_a?(feed_event)
          if lead.event_date > (Time.now - 7.days)
            count += 1
          end
        end
      end
    end
    count
  end


texts: Getting a list of all computer objects in each AD domain

texts:
So I wrote this script and although it does work I can't help but think that it can be more efficient with all the repetitive code. Can anyone offer any suggestions on making it fewer lines and eliminating the repeat lines?

$Domains = (Get-ADForest).domains | %{Get-ADDomain $_ | Select DistinguishedName,ReplicaDirectoryServers}

#Gets list of all Computer objects in each domain
foreach ($Domain in $Domains){
Write-Output "Working on $($Domain.DistinguishedName)"
  #Iterates through Computer array
   foreach ($Comp in (Get-ADComputer -Server $($Domain.ReplicaDirectoryServers[0]) -SearchBase $($Domain.DistinguishedName) -filter {OperatingSystem -notlike "*Server*"} -Properties     Name,LastLogonDate,DistinguishedName| ?{ $_.DistinguishedName -notlike "*OU=Disabled*" -and $_.DistinguishedName -notlike "*OU=Servers*"}|Select     Name,LastLogonDate,DistinguishedName)){
      #Performs test on date, if date is greater then $Days moves to $OU.
      if(((New-TimeSpan -Start ($Comp.LastLogonDate) -End (Get-Date)).days) -gt $Days -and $Exclusion -notcontains $Comp.name){
         $Computers += $Comp
         #Finds what OU each object should go to.  Checks if object is already in dumpster OU
         if($($domain.DistinguishedName) -like "*DomainA*"){
         Write-Output ((Get-Date).ToString('MM-dd-yyyy:hh:mm:ss') + ": Moved $($comp.DistinguishedName) to $DomainAOUDump") | Out-File $log -Append
         Move-ADObject -Identity $comp.DistinguishedName -Server $($Domain.ReplicaDirectoryServers[0]) -TargetPath $DomainAOUDump
         }
         elseif($($domain.DistinguishedName) -like "*DomainB*"){
         Write-Output ((Get-Date).ToString('MM-dd-yyyy:hh:mm:ss') + ": Moved $($comp.DistinguishedName) to $DomainBOUDump") | Out-File $log -Append
         Move-ADObject -Identity $comp.DistinguishedName -Server $($Domain.ReplicaDirectoryServers[0]) -TargetPath $DomainBOUDump
         }
         elseif($($domain.DistinguishedName) -like "*DomainC*"){
         Write-Output ((Get-Date).ToString('MM-dd-yyyy:hh:mm:ss') + ": Moved $($comp.DistinguishedName) to $DomainCOUDump") | Out-File $log -Append
         Move-ADObject -Identity $comp.DistinguishedName -Server $($Domain.ReplicaDirectoryServers[0]) -TargetPath $DomainCOUDump
         }
         elseif($($domain.DistinguishedName) -like "*DomainD*"){
         Write-Output ((Get-Date).ToString('MM-dd-yyyy:hh:mm:ss') + ": Moved $($comp.DistinguishedName) to $DomainDOUDump") | Out-File $log -Append
         Move-ADObject -Identity $comp.DistinguishedName -Server $($Domain.ReplicaDirectoryServers[0]) -TargetPath $DomainDOUDump
         }
         else{
         Write-Output ((Get-Date).ToString('MM-dd-yyyy:hh:mm:ss') + ": I don't know where $($comp.name) should be moved") | Out-File $log -Append
         }
       }
    }
 }


texts: Retrieve notifications and share across browser tabs

texts:
The idea of this code is to poll the server every 15 seconds to check for and update the notifications indicator. However, I'm not convinced I've done it right, as sometimes it seems to take an unusual amount of time to propagate across tabs and some users have reported that notifications "get stuck" and don't update at all. So here's the code, I think everything's right, but maybe I missed something.

$(function() {
    var LSping = "notify_lastping",
        LSresult = "notify_result",
        poll, interval = 15*1000,
        notif_icon = $("#notifs>a"),
        notif_body = $("#notifications");

    if( notif_icon.length < 1) return;

    var notbox = null,
        lastping = -1,
        running = false;

    function startPoll() {
        var delay = interval;
        if( lastping == -1) {
            delay = (+localStorage[LSping]+interval || 0) - Date.now();
            if( delay < 100) delay = 100;
        }
        lastping = localStorage[LSping] || 0;
        if( poll) clearTimeout(poll);
        poll = setTimeout(getNotifications,delay);
    }
    function getNotifications() {
        // storage event should reset the poll and update notices for us,
        // but just to be sure...
        if( lastping != (localStorage[LSping] || 0)) {
            updateNotifications(
                JSON.parse(localStorage[LSresult] || '{"html":"","count":0}'),
                true
            );
            return startPoll();
        }

        // inform other tabs that I'm on this
        localStorage[LSping] = Date.now();

        if( !running) {
            running = true;
            ajax("/notices").success(function(r) {
                running = false;
                localStorage[LSresult] = JSON.stringify(r);
                updateNotifications(r);
            }).failure(function(r) {
                running = false;
                return true; // use default error handler for AJAX callback
            });
        }

        startPoll();
    }
    function updateNotifications(r,fromStorage) {
        if( !fromStorage) {
            var oldids = notif_body.find("[data-id]").map(function() {return this.getAttribute("data-id");}).get();
        }
        notif_icon.attr("data-count",r.count);
        notif_body.html(r.html);
        document.title = (r.count ? "["+r.count+"] " : "")+document.title.replace(/^\[\d+\]\s*/,"");

        if( !fromStorage) {
            var newids = notif_body.find("[data-id]").map(function() {return this.getAttribute("data-id");}).get();
            var diff = $(newids).not(oldids).get(); // damn jQuery can do some weird stuff XD
            if( diff.length > 0) {
                // play notification sound if selected by user settings
            }
        }
    }

    getNotifications();

    $(window).on("storage",function(e) {
        e = e.originalEvent;
        if( e.key == LSping) {
            startPoll();
        }
        if( e.key == LSresult) {
            updateNotifications(JSON.parse(localStorage[LSresult]),true);
        }
    });
});

As far as I can tell there's no reason for the "loop" to stop. getNotifications() calls startPoll() regardless of the AJAX result. But like I said, maybe I missed something.


texts:
A website I have designed uses a nav menu that shows submenus on :hover. The initial site did not use any responsive design: it targeted only the desktop environment. I am now using responsive-design techniques to target mobile devices and tablets, many of which are touch based rather than mouse based.

The big issue I was facing (and that many other people seem to have also faced) was the hover-based nav menu: it works great in a mouse environment, but on touch devices, there is no reliable way to trigger the hover, making the page difficult to use.

The goal is this:

When a menu is hovered by a mouse, show the sub-menu.
When a menu is clicked with a mouse, open the link of the anchor tag.
The first time a menu is clicked by touch, show the sub menu.
The second time a menu is clicked by touch, open the link of the anchor tag.
Switch functionality seamlessly for tablets that also have mouse devices attached.

My team is not willing to sacrifice the hover effect on mouse-based machines. They like it and do not want to make the menus click based on all devices. I agree with this.

After looking around the net, I couldn't find any single solution for my problem. I put a few of them together and developed something that has tested well on Android, getting exactly the functionality I wanted.  Is there anything that can be improved and/or do you see any problems with this approach?

jQuery(document).ready(function() {
    var touched=false;
    jQuery(".nav").on('touchstart', 'li .has_children', function (e) {  touched=true; });
    jQuery("html").on('mousemove', function (e) { touched=false; });

    jQuery("html").on('click', updatePreviousTouched );

    jQuery(".nav").on('click', 'li .has_children', function (e) {
        updatePreviousTouched(e);
        if( touched ) {
            if (jQuery(this).data('clicked_once')) {
                jQuery(this).data('clicked_once', false);
                return true;
            } else {
                e.preventDefault();
                jQuery(this).trigger("mouseenter");
                jQuery(this).data('clicked_once', true);

            }
        }
        touched=false;
    });

    var previous_touched;
    function updatePreviousTouched(e) {
        if( typeof previous_touched != 'undefined' && previous_touched != null && !previous_touched.is( jQuery(e.target) ) ) {
            previous_touched.data('clicked_once', false);
        }
        previous_touched=jQuery(e.target);
    }
}

If this solution can be improved, please provide any suggestions. If you find that it doesn't work for you, please let me know that too. I'm posting it here to try to get any suggestions for improvement and to publish the idea so others can benefit from it.

Here are the results of my tests so far:

Windows 7 on major 5 browsers: works.
Android tablet on default browser: works.
Windows 7 laptop with touch-screen on IE and Chrome: Sort-of-works. The machine is running the desktop version of both browsers, so it is not triggering the "touchstart" event. Somewhere between the touchscreen and the browser, something is converting the touch into mouse events.  However, since the mouse is a non-removable part of this device, I don't consider this a failure. I would like it if it worked like a tablet, but there doesn't seem to be the technology available yet.
iOS iPad: This worked as desired before I wrote the above javascript.  It appears that ios does some of this hover/click magic for us behind the scenes.  I have a team member checking to see if my javascript broke the iOS functionality, I will edit this post once I get an answer.

Other notes:

This is only the menu for the desktop and tablet site. There is a different, click-based menu for the mobile site. I wouldn't recommend using this solution for a phone-sized device.


texts: Coderbyte SimpleSymbols challenge in Javascript

texts:
I am working on a CoderByte problem in JavaScript. I have solved the problem below. Although I am trying to figure out if there is an easier way to do it? I am guessing RegEx will come up, although I don't have experience with that yet.

From CoderByte:

  Using the JavaScript language, have the function SimpleSymbols(str)
  take the str parameter being passed and determine if it is an
  acceptable sequence by either returning the string true or false. The
  str parameter will be composed of + and = symbols with several letters
  between them (ie. ++d+===+c++==a) and for the string to be true each
  letter must be surrounded by a + symbol. So the string to the left
  would be false. The string will not be empty and will have at least
  one letter.

My implementation:

var str = "++d+===+c++=";

var simpleSymbols = function (str) {
    for (var i = 0; i < str.length; i++) {
        if (str[i] != '+' && str[i] != '=' && !(str[i] >= 'a' && str[i - 1] == '+' && str[i + 1] == '+')) {
            return false;
        }
    }
    return true;
}

simpleSymbols(str);


texts:
The Koch snowflake is a well known fractal. Beginning with an equilateral triangle, a smaller equilateral triangle is placed halfway along each edge of the shape. This process then repeats on each edge of the new shape. Here is my attempt to plot this in MATLAB.

clc, clearvars, close all;

length = 1; % Original side length of triangle
theta = 60*pi/180; % Angle of the equilateral triangle in radians

% Points of the original equilateral triangle
p1 = [0,0];
p2 = [1/2*length,length*sin(theta)];
p3 = [length,0];

flake_points = [p1; p2; p3]; % Vertices of the snowflake

for iteration = 1:7
    n_points = size(flake_points,1); % No. points currently in data
    new_triangle_points = nan(n_points*3,2); % New points to be added
    for i = 1:n_points
        p = flake_points(i,:);
        if i == n_points
            vector = flake_points(1,:)-flake_points(i,:);
        else
            % Vector between next point and current point
            vector = flake_points(i+1,:)-flake_points(i,:);
        end
        b1 = p + 1/3*vector; % Base point 1 of the new triangle
        b2 = p + 2/3*vector; % Base point 2 of the new triangle
        top = p + 1/2*vector + perp(vector)*length/3*sin(theta);
        new_triangle_points(3*i-2:3*i,:) = [b1; top; b2];
    end
    flake_points(end+1:end+9,:) = nan(9,2); % Add rows to data
    new_flake_points = nan(n_points*3+n_points,2);
    n = 1;
    for i = 1:n_points
        new_flake_points(n,:) = flake_points(i,:);
        index = 3*i-2;
        new_flake_points(n+1:n+3,:) = new_triangle_points(index:index+2,:);
        n = n + 4; % Three new points have been inserted,
                    % so we now skip to the next empty spaces
    end
    flake_points = new_flake_points;
    length = 1/3*length; % Revise length
end

plot(flake_points(:,1),flake_points(:,2),'w')
hold on; % Plot last data point with 1st (ie, close the loop)
plot([flake_points(1,1),flake_points(end,1)],...
    [flake_points(1,2),flake_points(end,2)],'w')
set(gca,'color',[0.1 0.1 0.1])
axis equal;
str = sprintf('Iteration: %d',iteration);
title(str, 'FontSize', 20);

Output:

Edit - This function is also required:

function p_vec = perp(vec)
% Returns the unit vector p_vec, which is perpendicular to the input
% 2D vector vec
%
% Inputs
%
%   vec : double
%       n_dimensions x 1
%       Input vector
%
% Outputs
%
%   p_vec : double
%       n_dimensions x 1
%       Perpendicular unit vector

p_vec(1) = -vec(2);
p_vec(2) = vec(1);

% Convert to unit vector
p_vec = p_vec / norm(p_vec);

end


texts: Printing out a tree set using pattern matching in Scala

texts:
I'm working on some exercises Scala by Example and I've implemented an excl() method on sets which removes an element from a set, and a toString method that converts a set to a string.

I'm practicing use pattern matching here. A bit concerned about shadowing my instance variables on the line

case NonEmptySet(elem, left, right)

Is there anything obvious that could be improved?

trait IntSet {
  def incl(x: Int): IntSet
  def excl(x: Int): IntSet
  def contains(x: Int): Boolean
}

case object EmptySet extends IntSet {
  def contains(x: Int): Boolean = false
  def incl(x: Int): IntSet = new NonEmptySet(x, EmptySet, EmptySet)
  def excl(x: Int) = this
  override def toString = "{}"
}

case class NonEmptySet(elem: Int, left: IntSet, right: IntSet) extends IntSet {
  def contains(x: Int): Boolean =
    if (x < elem) left contains x
      else if (x > elem) right contains x
      else true
  def incl(x: Int): IntSet =
    if (x < elem) NonEmptySet(elem, left incl x, right)
      else if (x > elem) NonEmptySet(elem, left, right incl x)
      else this
  def excl(x: Int): IntSet = {
    def combine(left: IntSet, right: IntSet): IntSet = {
      left match {
        case EmptySet => right
        case NonEmptySet(elem, ll, lr) => NonEmptySet(elem, combine(ll, lr), right)
      }
    }
    if (x < elem) new NonEmptySet(elem, left excl x, right)
    else if (x > elem) new NonEmptySet(elem, left, right excl x)
    else combine(left, right)
  }
  override def toString(): String = {
    def listElements(comma: Boolean, set: IntSet) : String = {
      set match {
        case EmptySet => ""
        case NonEmptySet(elem, left, right) => {
          val rightPart = elem + listElements(true, right)
          val list = left match {
            case EmptySet => rightPart
            case NonEmptySet(le, ll, lr) => listElements(false, left) + ", " + rightPart
          }
          (if (comma) ", " else "") + list
        }
      }
    }
    '{' + listElements(false, this) + '}'
  }

}

var subset = EmptySet incl 2
var set = subset incl 3 incl 4 incl 8 incl 9 incl 10 incl 11 excl 4
println(set contains 6)
println(set.contains(6))
println(set contains 2)
println(set incl 4 incl 6 excl 2)


texts: Partition lists into sublists based on condition in haskell?

texts:
Need to partition a list of integers into sublists if it matches with an integer that is passed in. For example if the integer passed in is 3, [1,2,3,4,3,5,3] will become [[1,2,3],[4,3],[5,3]], How can i accomplish this?
listToSublist :: [Int] -> x -> [[Int]]
-- Looks pathetic but this is honestly as far as I have come without errors,
--I'm in desperate need to do this would appreciate any help


texts:
I need to perform SQL query which will get products from database based on few dimensions which I will pass in URL.

import itertools

sql_where = ''
dimensions = ['a','b', 'c', 'd', 'e', 'f', 'f2', 'g']

for dimension in dimensions:
    for onetwo, direction in zip( range(1, 3), itertools.cycle('><') ):
        globals()[dimension+str(onetwo)] = str( request.GET.get( dimension+str(onetwo) ) )
        sql_where += " AND ( `{dimension}` {direction}= '{get_dimension}' OR '{get_dimension}' = ('None' OR '') )".format(dimension=dimension, direction=direction, get_dimension=globals()[dimension+str(onetwo)])

sql = """SELECT * FROM t_wishbone_dimensions WHERE 1=1""" + sql_where
print sql

Example output for /search?a1=34&a2=37&c1=50&c2=75

SELECT * FROM t_wishbone_dimensions
WHERE 1=1
AND ( `a` >= '34' OR '34' = ('None' OR '') )
AND ( `a` <= '37' OR '37' = ('None' OR '') )
AND ( `b` >= 'None' OR 'None' = ('None' OR '') )
AND ( `b` <= 'None' OR 'None' = ('None' OR '') )
AND ( `c` >= '50' OR '50' = ('None' OR '') )
AND ( `c` <= '75' OR '75' = ('None' OR '') )
AND ( `d` >= 'None' OR 'None' = ('None' OR '') )
AND ( `d` <= 'None' OR 'None' = ('None' OR '') )
AND ( `e` >= 'None' OR 'None' = ('None' OR '') )
AND ( `e` <= 'None' OR 'None' = ('None' OR '') )
AND ( `f` >= 'None' OR 'None' = ('None' OR '') )
AND ( `f` <= 'None' OR 'None' = ('None' OR '') )
AND ( `f2` >= 'None' OR 'None' = ('None' OR '') )
AND ( `f2` <= 'None' OR 'None' = ('None' OR '') )
AND ( `g` >= 'None' OR 'None' = ('None' OR '') )
AND ( `g` <= 'None' OR 'None' = ('None' OR '') )

What do you think about my solution?


texts:
I've written the following code:

{- ...
   ...
   ... -}

data Ellipsoid
data Halfplane
data Intersection

data PointSet s a where
    Halfplane :: RealFrac a =>
                 a -> a -> a -> (a -> a -> Bool) -> a ->
                 PointSet Halfplane a
    Ellipsoid :: RealFrac a =>
                 a -> a -> a -> (a -> a -> Bool) -> a ->
                 PointSet Ellipsoid a
    Intersection :: [PointSet s a] -> PointSet Intersection a

type TestFunc a = RealFrac a => (a -> a -> a ->  Bool)

test :: (Show  a) => PointSet t a -> TestFunc a
test (Ellipsoid a b c f r) = f'
                       where f' z y x = ((x/a)^2 + (y/b)^2 + (z/c)^2) `f` r
test (Halfplane a b c f t) = f'
                       where f' z y x = (a*x + b*y + c*z) `f` t
test (Intersection ps) =     f'
        where f' z y x = and . map ($ x) $ map ($ y) $ map ($ z) ts
              ts = map test ps

In particular I'd like to have input on f' z y x = and . map ($ x) $ map ($ y) $ map ($ z) ts, whether there is a way to express this more succinctly.

Of course, I'm happy about any other comment as well.


texts: Prevent Variable Overflow from InputBox user error

texts:
I was writing some code that required the user to input a number, which was then stored in a variable.  While testing the code I input a number larger than the variable type would allow and I got an variable overflow error.  So I wrote this code to prevent that from happening. It works, but I was hoping there was a more concise way to do it, or even a function already part of VBA that I could use.

Sub PreventOverflow()

    Dim IsThisANumber As String
    Dim Number As Integer
    Dim PreventOverflow As Long
    Dim Cancel As VbMsgBoxResult

    Number = 0
    PreventOverflow = 0

    IsThisANumber = InputBox("Enter a number less than 32768")

    Do While Number = 0

        Do While PreventOverflow = 0
            If IsNumeric(IsThisANumber) = True Then
                If Len(IsThisANumber) < 6 Then
                    PreventOverflow = IsThisANumber
                Else
                    IsThisANumber = InputBox("Your number was not less than 32768" & vbNewLine & "Please enter a number less than 32768")
                    PreventOverflow = 0
                End If
            ElseIf IsThisANumber <> "" Then
                IsThisANumber = InputBox("Your did not enter a number" & vbNewLine & "Plese enter a number less than 32768")
                PreventOverflow = 0
            Else
                Cancel = MsgBox("You did not enter a number.  Do you want to continue?", vbYesNo)
                If Cancel = vbNo Then
                    Exit Sub
                Else
                    IsThisANumber = InputBox("Enter a number less than 32768")
                    PreventOverflow = 0
                End If
            End If
        Loop

        If PreventOverflow < 1 Or PreventOverflow > 32767 Then
            IsThisANumber = InputBox("Your number was not less than 32768" & vbNewLine & "Please enter a number less than 32768")
            PreventOverflow = 0
        Else
            Number = PreventOverflow
        End If
    Loop

End Sub


texts:
I have two functions now with very similar functionality, and would like to merge them into one more generic function. The only difference between those two functions is that one handles json input file and the other xml input file.
I could use if statements to achieve this, but I find it cumbersome, other suggestions would be much appreciated!

def update_json_type_report(self, testcase_id, did_any_test_fail, test_case_steps):
    print "Adding results to test case id: %s" % testcase_id

    fail_or_pass = '(/) ' # initialize test to pass

    expected_result = {
        "result":""
    }

    for i, step in enumerate(test_case_steps):
        for tests in self.parsed_report_file["suites"]:
            for test in tests["tests"]:
                tmp_result = ""
                if test["name"] == test_case_steps[i]['step']['raw'] and test["state"]:
                    if "error" in test:
                        fail_or_pass = '(x) '
                        did_any_test_fail = 3
                        tmp_result += fail_or_pass + test["error"] + '\n'
                    else:
                        # can have many tests per step, append them all in one string adding '\n' at end of each line
                        tmp_result += fail_or_pass + test["name"] + '\n'

                    break
            #import pdb; pdb.set_trace()
            expected_result['result'] = tmp_result
            if tmp_result:
                self.jira_obj.send_put('xray', 'test/%s/steps/%s' % (testcase_id, test_case_steps[i]['id']), expected_result)

    return did_any_test_fail

def update_xml_type_report(self, testcase_id, did_any_test_fail, test_case_steps):
    print "Adding results to test case id: %s" % testcase_id

    fail_or_pass = '(/) ' # initialize test to pass

    expected_result = {
        "result":""
    }

    for i, step in enumerate(test_case_steps):
        for xml_testsuite in self.parsed_report_file:
            for xml_testcase in xml_testsuite.iter('testcase'):
                tmp_result = ""
                if xml_testcase.attrib["name"] == test_case_steps[i]['step']['raw'] and "hook" not in xml_testcase.attrib["name"]:
                    if xml_testcase.find('system-err') is not None:
                        fail_or_pass = '(x) '
                        did_any_test_fail = 3
                        tmp_result += fail_or_pass + xml_testcase.find('system-err').text + '\n'
                    else:
                        # can have many tests per step, append them all in one string adding '\n' at end of each line
                        tmp_result += fail_or_pass + xml_testcase.attrib["name"] + '\n'

                    break

            expected_result['result'] = tmp_result
            if tmp_result:
                self.jira_obj.send_put('xray', 'test/%s/steps/%s' % (testcase_id, test_case_steps[i]['id']), expected_result)

    return did_any_test_fail


texts:
I am new to PHP and was just wondering if there is a better way to write the following OR if it would make any difference to use elseif here instead of multiple if statements - especially if the options in questions might be more than in the example here (the current code is working).

Note: I cannot use switch here since the haystack string can contain multiple of the needle strings.

$errorList .= "Some text
";
    if(strpos($errorDetails, "emailInvalid") !== false){
        $errorList .= "
Some text
";
    }
    if(strpos($errorDetails, "passLength") !== false){
        $errorList .= "
Some text
";
    }
    if(strpos($errorDetails, "passLowerCase") !== false){
        $errorList .= "
Some text
";
    }
    if(strpos($errorDetails, "passUpperCase") !== false){
        $errorList .= "
Some text
";
    }
    if(strpos($errorDetails, "passNumberSymbol") !== false){
        $errorList .= "
Some text
";
    }
    if(strpos($errorDetails, "passMatch") !== false){
        $errorList .= "
Some text
";
    }
$errorList .= "
";
echo $errorList;


texts: Create a divisors list and identify primary numbers

texts:
I tackled a beginners' exercise: "asks the user for a number and then prints out a list of all the divisors of that number."
The workflow I established is: input an integer number, say x; add a variable which value is x/2, say y; declare a divisors list.
If x is greater than 4 iterate between 2 and y+1; if the remainder is zero append it the the divisors list.
If divisors list is empty or if the input number is smaller than 4 return: this is a primary number.
else, return divisors list.
I ended up with the following solution. It does the job, but isn't good enough, as it has the following issues:
What is the python's input number limit? Currently, I have no limit which is wrong as it beyond the computational capacities of any computer.
I suspect my else statement isn't tidy enough. It can be shorter... but how?
If the number is lower than 4, the script returns twice the message "the number you entered is a primary number". I could fix it with an ad-hoc solution - but it should be solved through an algorithm not in a manual manner (...at least if I try to learn coding).
I ended up iterating in range of 2 and y+2 rather y+1 as I thought. I solved it manually but I don't understand why it isn't y+1.
num = int(input("Please select a number between: "))
y = num/2
if not y==0:
    y=int(y-0.5)

list_range = list(range(2,y+2))

divisors_list = []
if num < 4:
    print("The number you entered is a primary number")
else:
    for i in list_range:
        if num%i ==0:
            divisors_list.append(i)

if not divisors_list:
    print("The number you entered is a primary number")
else:
    print(divisors_list)


texts:
My code does the following:

There are two  Maps with properties. I need to check if properties with the same key and value already exist, and if they do, throw an exception.

    Map<String, Object> existingProperties = requires.get(requiresIndex).getProperties();
    for (Map.Entry<String, Object> property : properties.entrySet()) {
        if (existingProperties.containsKey(property.getKey())){
            if (existingProperties.get(property.getKey()) instanceof String && property.getValue() instanceof String ){
                String existingValue = (String) existingProperties.get(property.getKey());
                String newValue = (String) property.getValue();
                if (existingValue.equals(newValue)){
                    throw new Exception("Property " + property.getKey() + " is existsing with value " + newValue + "in requires " + requiresName);
                }
            }
        }
    }

We are working on Java 8. Is there a better/shorter way to write it?


texts: "switch" with intervals to snap to a 15-minute mark

texts:
I am working with dates and times which are not necessarily "on point", which means that while I need the times in fixed quarterly sections, I can't make sure that the saved timestamp isn't a little off.

I need xx:00, xx:15, xx:30 and xx:45 obviously, but the times could be yy:03, yy:14 and alike, you get the hang of it...

Normally I would use a switch statement to select what is about to happen, but in PHP switch does not work with intervals.

Currently, I am stuck with this code:

$temp_minute = date('i', $tdd->datum);

if( ( $temp_minute > 10 ) && ( $temp_minute < 20 ) ) { $minute = '15'; }
elseif( ( $temp_minute > 25 ) && ( $temp_minute < 35 ) ) { $minute = '30'; }
elseif( ( $temp_minute > 40 ) && ( $temp_minute < 50 ) ) { $minute = '45'; }
else { $minute = '00'; }

This seems to be far from elegant but gets the job done.

Are there any "nicer" ways around this, given the case that I might need to add more sections or am I bound to elseif statements?


texts: Getting rid of an inordinate use of the `instanceof` function

texts:
I am working with a library that has a base class Base, and three class descending from it Destination, Amenity and Landmarks.
The Base class looks something like this

public class Base {
    public Integer id;
    public String externalId;

    public Base() {
    }

    public int getId() {
        return this.id;
    }

    public String getExternalId() {
        return this.externalId != null ? this.externalId : "";
    }
}

The children classes look like this

public class Destination extends Base implements Parcelable {
    private String name;
    private String description;
    private Point[] points

    public String getName() {
        return this.name;
    }

    public String getDescription() {
        return this.description;
    }

    public Point[] getPoints(){
        return this.points;
    }

}

The important thing to note here is that the three child classes have the points property and the getPoints getter for accessing it. If it was my implementation, I would bring the points field into the base class to avoid replicating multiple times in the child classes but like I said, it's a library and I cannot modify the source.
While working with the library I have ran into a situation where I have had to use the instanceof function multiple times and since this is considered a code smell, I'd like to know if there is a better way of going about it. The situation I'm describing happens when I try to get one of the child objects when a point item is specidied, the code looks like this right now

public static <T> T getCurrentMapObjectWithPoint(Point point, T [] bases){

        T base = null;
        for(T model: bases){
            Point[] points = getpointsArrayFromMapObject(model);
            for(Point currentpoint: points){
                if(currentpoint.id.equals(point.id)){
                   return base;
                }
            }
        }
        return base;
    }

    private static <T> point[] getpointsArrayFromMapObject(T base){
        if(base instanceof Amenity ){
            return ((Amenity) base).getpoints();
        } else if(base instanceof Destination){
            return ((Destination) base).getpoints();
        } else if (base instanceof LandMark){
            return ((LandMark) base).getpoints();
        }
        return new point[]{};
    }

So simply put, given a Point and list of map items(T[] base - which means and array of either Amenity, Destination or Landmark) I'm trying to figure out which Amenity, Destination or LandMark the point belongs to which means I have to go throgh the list of map items and for each item, go through the points for that item and whenever the point id is equal to the id of the point given at the start I break out of the loop and return the current map item. Is there a better way of doing this without using instanceof multiple times?


texts:
I was reading about private variables and functions in Python and I managed to get almost everything except one thing.

Is it recommended to write underscore before variables defined inside a function?

Here is the code so it can be more clear:

Version 1:

class House():

    def __init__(self):

        self.color = "RED"
        self._discount_coefficient = 0.8

    def get_total_charges(self, json_from_communal_company):

        _water_price        = json_from_communal_company["waterPrice"]
        _electricity_price  = json_from_communal_company["electricityPrice"]

        _total_charges = self._discount_coefficient * (_water_price + _electricity_price)

        return _total_charges

Version 2:

class House():

    def __init__(self):

        self.color = "RED"
        self._discount_coefficient = 0.8

    def get_total_charges(self, json_from_communal_company):

        water_price        = json_from_communal_company["waterPrice"]
        electricity_price  = json_from_communal_company["electricityPrice"]

        total_charges = self._discount_coefficient * (water_price + electricity_price)

        return total_charges

I know that variable _discount_coefficient needs to have underscore, but I am not sure if variables water_price, electricity_price and total_charges should have underscore or not.

Can someone tell me which version is better and why?


texts: Aggregate conditional logic test results iterated over changing row selections

texts:
This for-loop is the biggest bottleneck in my project, and I'm curious whether there is an opportunity to speed it up by improving the grammar or by using a different strategy altogether, perhaps. I'm a noob to Python and migrating this from Excel.

Here's some sample data and the scheme.  j's range is actually 25k and i's about 1k, so it takes quite a while.

Functionally, it selects rows in df1 where a string in any of the 'typeX' columns matches a particular element in df2_columns, then tests the sl_pt element on each of those rows. It creates a 'dummy' array s to reduce the 3-part 'or' test down to a T/F, and performs some math on the count of T's as well as the count of F's.  It tests with every sl_pt element and then goes to the next element in df2_columns, rinse, repeat.

import pandas as pd
import numpy as np
import functools as ft

df1 = pd.DataFrame({'type1' : ['A1_v3', 'A2_v2', 'A1_v3', 'B1_v2'],
                    'type2' : ['A1_vr1', 'A2_vr3', 'A1_vr3', 'B1_vr2'],
                    'type3' : ['A1_vp4', 'A2_vp2', 'A1_vp3', 'B1_vp4'],
                    'mae1' : [14, 16, 4, 63],
                    'mae2' : [17, 29, 38, 63],
                    'mae3' : [27, 29, 77, 63],
                    'mfe1' : [48, 31, 59, 0],
                    'mfe2' : [79, 37, 59, 14],
                    'mfe3' : [79, 108, 71, 36]})

df2 = pd.DataFrame({'sl_pt' : [[22, 62], [22, 63], [22, 64], [22, 66], [22, 68], [22, 70]]})

df2_columns = ['A1_v3', 'A2_vr3', 'B1_vp4']

for i in range(3):
    tag = ft.reduce(np.logical_or, [df1['type{}'.format(k)].str.startswith(df2_columns[i]) for k in range(1,4)])
    selection = df1.loc[tag]
    for j in range(6):
        sl = df2['sl_pt'][j][0]
        pt = df2['sl_pt'][j][1]
        s = ft.reduce(np.logical_or, [(selection['mae{}'.format(m)] >= 0) & (selection['mae{}'.format(m)] <= sl) & (selection['mfe{}'.format(m)] >= pt) for m in range(1,4)])
        df2.loc[j, df2_columns[i]] = sum(s) * pt * 10 + (len(s) - sum(s)) * sl * -10


texts: Two sum problem implementation with Hashtable

texts:
Problem statement:

  Given an array of integers, return indices of the two numbers such
  that they add up to a specific target. You may assume that each input
  would have exactly one solution, and you may not use the same element
  twice.

  Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1]

I have a working Java implementation with both time and space complexity of \$O(n)\$. However, I am looking for feedbacks on how to write better, more elegant code. Any suggestions on style, simplicity,  comments, etc., are welcome.

Note: function signature is provided to me in the interview, not mine. Otherwise I would return a Pair instead of int[].

import java.util.Hashtable;

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int loadFactor = 3;
        //key: num, value: num's parter's idx, if exists
        Hashtable<Integer, Integer> parterIdxHash = new Hashtable<Integer, Integer>(loadFactor*nums.length);
        for(int i = 0; i < nums.length; i++){
            int curVal = nums[i];
            Integer parterIdx = parterIdxHash.get(curVal);

            //found its parter
            if(parterIdx != null)
                return new int[]{parterIdx, i}; //parterIdx first because it's eariler in the array

            int parterVal = target - curVal;
            parterIdxHash.put(parterVal, i);

        }

        //should never reach here!
        return new int[]{-1, -1};
    }
}


texts: Parsing nested JSON with Haskell and Aeson

texts:
I'm trying to reduce nested JSON data using Haskell and Aeson without creating data/record types.
The following code works, but seems ugly and unreadable.
Any advice on cleaning this up would be great.

Thank you

import GHC.Exts
import Data.Maybe (fromJust)
import Data.Text (Text)
import Data.Aeson
import qualified Data.HashMap.Strict as M

testVal :: Value
testVal = Object $ fromList [
  ("items", Array $ fromList [
    (Object $ fromList [
      ("entity", (Object $ fromList [
        ("uuid", String "needed-value1")]))]),
    (Object $ fromList [
      ("entity", (Object $ fromList [
        ("uuid", String "needed-value2")]))])
    ])]

getItems :: Value -> Value
getItems (Object o) = fromJust $ M.lookup "items" o

getEntities :: Value -> Value
getEntities (Array a) = Array $ fmap (\(Object o) -> fromJust $ M.lookup "entity" o) a

getUuids :: Value -> Value
getUuids (Array a) = Array $ fmap (\(Object o) -> fromJust $ M.lookup "uuid" o) a

getTexts :: Value -> [Text]
getTexts (Array a) = toList $ fmap (\(String s) -> s) a

someFunc :: IO ()
someFunc = do
  let items = getItems testVal
      entities = getEntities items
      uuids = getUuids entities
      texts = getTexts uuids
  print texts

output:

["needed-value1","needed-value2"]


texts: Class that only creates an instance of a new game

texts:
I am creating a game. I am at the final phase for the underlying basis and I am wondering whether what I am doing is recommended- if it's convention.

All this class does is create an instance of the game. That's it. The game instance takes care of the rest (i.e attaching the menu screen to the screenManager (i.e displaying the menu screen))

As a result, this class complains that we're not using the value. But that's exactly what we want, we HAVE no use of this result. I just want to know, is this OK?

    public final class RunGame
{
    private RunGame() {}

    public static void main(String[] args){
       Game game = new Game(); // We want to start a new instance of the game, but we have no use with the result!
    }
}


texts:
I've started my personal website with HTML5.
I would like to get it review to see if I am using the correct schema.

I am looking to get feedback about the structure of HTML5 elements. I think I am overdoing some of the things in the code.

html,
body {
  font-family: Verdana, Geneva, Tahoma, sans-serif;
  font-size: 12px;
  padding: 0;
  margin: 0;
}

a {
  cursor: pointer;
}

#container {
  margin: 0 auto;
  width: 1000px;
}

#midcontainer {
  margin: 0 auto;
  width: 1000px;
}

#midcontainer::before {
  clear: both;
}

#midcontainer::after {
  clear: both;
}

header {
  background: #ff4242;
  height: 30px;
  padding: 20px 0;
}

header span {
  color: #fff;
  float: left;
  font-size: 24px;
}

header span.your {
  font-weight: bold;
}

nav {
  line-height: 30px
}

nav ul {
  float: right;
  list-style: none;
  margin: 0;
  padding: 0;
}

nav ul li {
  display: inline;
  margin-left: 20px;
}

nav ul li a {
  color: #fff;
  text-decoration: none;
}

nav ul li a:hover {
  border-bottom: 1px solid #fff;
}

.intro {
  background: #f0f2eb;
  color: #333;
  text-align: center;
  margin-bottom: 50px;
  padding: 100px 50px;
}

.intro h2 {
  font-size: 48px;
}

.intro span {
  font-size: 32px;
  margin-top: -30px;
  margin-bottom: 20px;
  display: block;
  font-weight: bold;
}

.intro button {
  background: #f0f2eb;
  border: 2px solid #ff4242;
  font-size: 16px;
  color: #333;
  padding: 20px 30px;
  text-transform: uppercase;
}

.intro button:hover {
  background: #ff4242;
  border: 2px solid #ff4242;
  color: #fff;
}

.photography,
.code,
.graphicdesign {
  float: left;
  width: 33.3%;
  text-align: center;
}

footer {
  background: #333;
  color: #fff;
  clear: left;
  display: block;
  margin: 20px 0 0 0;
  padding: 20px 40px;
  text-align: center;
}

footer a {
  text-decoration: none;
  color: #fff;
  border-bottom: 2px solid #fff;
  padding-bottom: 3px;
}

footer ul {
  list-style: none;
}

footer ul li {
  display: inline;
  margin-right: 25px;
}

footer ul li a {
  text-decoration: none;
  color: #ff4242;
  border: none;
}

    YOURNAME

Home

About Me

Gallery

Blog

Conact

Who is this guy?

  Dude, myth or mega designer!
  <button>get to know me</button>

photography

Code

Graphic Design

Facebook

Twitter

Youtube

Instagram

Designed by your name


texts:
It was suggested I place this code here. I had posted it on StackOverflow for a kind of review.

I have tried to generate Hamming numbers using primes but the speed of the generation slows the higher the number generated and the prime list grew proportionately. I then started to find if a number could be factored down to 2,3 or 5. This was faster but still far away from linear.

Then I found in Excel that a candidate number when evenly divided by one of 2,3 or 5 can be found in previously generated hamming numbers if it is itself a Hamming number.

I thought this approach would result in faster Hammond number generation.

I have played with generating the last of a large set of Hamming numbers using my standard methods. Once the final set is generated all previous Hammings can selectively be extracted from it. The last set just takes to long to generate even though once it is, the speed becomes linear. I just need a faster way to generate any Hamming list.

I do not know if anyone has ever tried to exploit the fact that each successive candidate number can be tested for Hamming status by dividing it by one of 2,3 or 5 and testing if the quotient is a member of the Hamming list generated to that point.

The function takes two parameters, a seed list of (reversed) Hamming numbers less than 10 and a candidate list of any size. I prefer to us a list of [2,3,5] multiples I call base

base = scanl (\b a -> a+b) 2 $ cycle [1,1,1,1,2,1,1,2,2,1,1,2,2,1,1,2,1,1,1,1,2,2]

hamx ls (x:xs)
   | even x        && elem (div x 2) ls = hamx (x:ls) xs
   | mod  x 3 == 0 && elem (div x 3) ls = hamx (x:ls) xs
   | mod  x 5 == 0 && elem (div x 5) ls = hamx (x:ls) xs
   | null xs = ls
   | otherwise = hamx ls xs

I tried filter and any and others in place of elem. The list generates in reverse. The elem finds Hamming matches faster from the bottom and new Hamming numbers appear also at the bottom. So, the bottom is the top.

I am now working on the 2,3,5 Hamming multiples used in other algorithms. I know how not to generate duplicates. I might be able to integrate these select multiples into the above code. For example, the select list will only use 15 multiples of 5 in 6,103,515,625. All of the 10s are already in the 2 multiples and many 5 multiples are found in 3 multiples. The only 3 multiples needed are from odd Hamming numbers. All 2 multiples are needed.


texts:
Seems to work fine, I guess it won't work if the destination array's size is not defined by a macro, but a variable or something else, I thought about adding a third argument which is the size and let the user enter it, but that might be worse.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100

char *ptr_str_cat(char *dest, const char* src){
    char *original;
    original = dest;
    if((strlen(dest) + strlen(src)) > MAX_SIZE){
        puts("The source string is too big for the destination");
        exit(EXIT_FAILURE);
    }
    dest = strchr(dest, '\0');
    *dest = '0';
    while((*dest++ = *src++) != '\0'){
        ; /*do nothing*/
    }
    return original;
}

int main(void){
    char dest [MAX_SIZE];
    char source [MAX_SIZE];
    puts("Enter the destination string");
    fgets(dest, sizeof(dest), stdin);
    dest[strlen(dest) -1 ] = '\0'; /*Remove trailing newline*/
    puts("Enter the source string");
    fgets(source, sizeof(source), stdin);

    printf("%s", ptr_str_cat(dest, source));

    return 0;
}


texts: Printing lines in a file, filtering by the first column

texts:
I am setting up a project which involves a lot of data analysis, each data point represented by a line in a large text file. In order to test for certain types of data, I added a tag to each line (It needs to remain in one file, though). Now I want to conveniently choose which type of data I want to include, currently I have five types (positive, negative, neutral, objective, objective-OR-neutral). Coming from C, I wrote my parse(filename) function the following way:

# parsing.py
# flags
POS = 1
NEG = 2
NEU = 4
OBJ = 8
OON = 16

# 'flag transformation dictionary'
ftd = {u'positive': POS,
       u'negative': NEG,
       u'neutral': NEU,
       u'objective': OBJ,
       u'objective-OR-neutral': OON}

# Read flagged data from file, return only entries with the right flag.
# Each line is: <flag><\t><content>
def parse(f_loc, flags=0):
    for line in open(f_loc):
        flag, content = line.strip().split('\t')
        if ftd[flag] & flags:  # this wouldn't be as pretty with kwargs
            yield content

Using this utility function somewhere else would then look like this:

# parsing_test.py
from parsing import parse, POS, NEG, NEU, OBJ, OON

# print all data flagged as 'positive', 'negative', or 'neutral'
for entry in parse('file.txt', POS | NEG | NEU):
    print(entry)

# print all data, no matter the flag
for entry in parse('file.txt', POS | NEG | NEU | OBJ | OON):
    print(entry)

I am just starting this project and am very conscious about good style (especially intuitiveness, extendability, robustness, and speed), so I would appreciate any criticism.


texts: Filter by a distinguishing field when making publications using meteor

texts:
In my publications with meteor.js, I find myself repeating the same style of code and would like a cleaner approach. For example:

I have a users collection that has the distinguishing field school, an identifier that tells me by which school, I should filter what information on the server so that I don't send the wrong school the wrong information. Currently, I

Meteor.publish('schoolDirectory', function (schoolId) {
        return Meteor.users.find({'profile.school': schoolId}});
});

Where I take in the schoolId on the client, and filter appropriately. I am not sure of the security implications there and have tried switching to a style where I use the authenticated users object to determine the school on the server before publishing any more data like so:

Meteor.publish('schoolDirectory', function () {
             var currentUser = Meteor.users.findOne({_id: this.userId});
             var schoolId = Schools.findOne({_id: currentUser.profile.school});
            return Meteor.users.find({'profile.school': schoolId}});
    });

This has the issue of not being able to publish data for anonymous users, anyone have any suggestions on how to improve the code base to use this distinguishing field globally ?


texts: Java beans performance with object inside object

texts:
I am developing a bean class which has multi face properties (name has first name, last name and middle name). The object is going to be used to create an xml file. Please compare my two methods to incorporate the same in my application.

Method 1:

public class SampleVO {
String firstName;
String middleName;
String lastName;
// getters and setters
}

Method 2:

//Main object
public class SampleVO1 {
NameVO name = new NameVO();
// getters and setters
}
//Name object
public class NameVO {
    String firstName;
    String middleName;
    String lastName;
    // getters and setters
}

Note: Above is just a sample. The requirement is to group a set of properties. In Which way of the above performance/code standards will be good?


texts: Project Euler 42 - finding triangle number V2

texts:
This is my revised solution to Problem 42 from Project Euler, based on suggestions in this original post Project Euler 42 - Finding triangle numbers

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

namespace ProjectEuler
{
    class p42trianglenumber
    {
        // p42. tn = ½n(n+1)
        // A=1, B=2, etc. case insensitive.
        public static void NotMain()
        {
            var sw = new Stopwatch();
            sw.Start();
            int numberTriangleWords = 0;
            string[] words = ReturnStringArray("p042_words.txt");
            int[] triangleNumbers = BuildTriangleNumber();

            foreach (string word in words)
            {
                var score = GetScore(word);

                if (triangleNumbers.Contains(score))
                {
                    numberTriangleWords++;
                }
            }
            sw.Stop();
            Console.WriteLine(numberTriangleWords + Environment.NewLine + sw.ElapsedMilliseconds.ToString() + "ms");
            Console.ReadLine();
        }

        private static string[] ReturnStringArray(string fileLocation)
        {
            StreamReader sr = new StreamReader(fileLocation);
            string[] words = sr.ReadLine().Split(',');
            return words;
        }

        private static bool IsWordTriangleNumber(int wordVal, int[] triangleNumbers)
        {
            return (triangleNumbers.Contains(wordVal));
        }

        private static int[] BuildTriangleNumber()
        {
            int triangleNumberValue = 0;
            int[] triangleNumbers = new int[50];

            for (int i = 0; i < 50; i++)
            {
                if (i == 0)
                    triangleNumbers[i] = triangleNumberValue;
                else
                {
                    triangleNumberValue += i;
                    triangleNumbers[i] = triangleNumberValue;
                }
            }
            return triangleNumbers;
        }

        private static int GetScore(string word)
        {
            var total = 0;
            foreach (var letter in word)
            {
                total += GetScore(letter);
            }
            return total;
        }

        private static int GetScore(char letter)
        {
            var start = char.IsLower(letter) ? 'a' : 'A';
            var score = (int)letter - (int)start + 1;
            if (score < 0 || score > 26) return 0;
            return score;
        }
    }
}


texts:
I've wrote a calculator in Java with a GUI using swing.
Here are the classes:

Control.java:

public class Control {
    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        Gui gui = new Gui(calculator);
        gui.setVisible(true);
        boolean exit = false;
        while(!exit) {

        }
    }
}

Gui.java:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Gui extends JFrame {
    Calculator calculator;
    public Gui(Calculator calculator) {
        this.calculator = calculator;
        //The frame
        setSize(400, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        //Panel for Text-output
        JPanel textPanel = new JPanel();
        textPanel.setPreferredSize(new Dimension(400,70));
        JTextField textfield = new JTextField("");
        textfield.setPreferredSize(new Dimension(380,70));
        textfield.setHorizontalAlignment(JTextField.RIGHT);
        textPanel.add(textfield);
        add(textPanel, BorderLayout.NORTH);

        //Panel for buttons
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new java.awt.GridLayout(4, 5));
        buttonPanel.setPreferredSize(new Dimension(380, 280));

        //Buttons
        String[] buttonText = {
            "7", "8", "9", "+", "<-", "4", "5", "6", "-", "(", "1", "2", "3",
            "*", ")", "0", ",", "C", "/", "="
        };
        JButton button[] = new JButton[20];
        for(int i = 0; i < 20; i++) {
            button[i] = new JButton(buttonText[i]);
            button[i].addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent event) {
                    for(int i = 0; i < 20; i++) {

                        if(event.getSource() == button[i]) {

                            //Delete last character button
                            if(i == 4) {
                                String text = textfield.getText().toString();
                                text = text.substring(0, text.length()-1);
                                textfield.setText(text);
                            }

                            //Delete all button
                            else if(i == 17) {
                                textfield.setText("");
                            }

                            //"="-button
                            else if(i == 19) {
                                String text = textfield.getText().toString();
                                String output = "";
                                try {
                                    output = calculator.calculate(text);
                                }
                                catch (Exception ex) {

                                }
                                textfield.setText(output);
                            }

                            //other buttons
                            else {
                                String text = button[i].getText().toString();
                                String fieldText = textfield.getText().toString();
                                textfield.setText(fieldText + text);
                            }

                        }
                    }
                }
            });
            buttonPanel.add(button[i]);
        }

        add(buttonPanel, BorderLayout.SOUTH);
    }
}

Calculator.java:

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class Calculator {
    public String calculate(String text) throws Exception {
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
        Object sol = scriptEngine.eval(text);
        String solution = sol + "";
        return solution;
    }
}

What do you think about it? Do you have any suggestions on improving the code?


texts: Compute and print the sum and mean of name and value pairs

texts:
I'm just looking for more feedback on style/approach regarding this small problem. Also, if you have tips to make it more readable or C++-like, please let me know.

Also, why is the problem asking for the sum and mean of each name and all names, while the sum of a single element is itself? Am I missing anything in terms of answering the question?

#include <stdio.h>
#include <stdlib.h>
#include <map>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>

/********************************************************************
 * Read a sequence of possibly whitespace-separated (name,value)
 * pairs, where the name is a single whitespace-separated word and
 * the value is an integer or floating-point value. Compute and print
 * the sum and mean for each name and the sum and mean for all names
 * ******************************************************************/

using namespace std;

std::multimap<string,float> _map;

istream& operator>>(istream& stream, pair<string,float> &in ) {
    return stream >> in.first >> in.second;
}

ostream& operator<<(ostream& stream, pair<string,float> &out ) {
    return stream << "(" << out.first
                  << ", " << out.second << ")" << endl;
}

int main( int argc, char *argv[ ] ) {
    istream *is = &cin;
    do {
        pair<string,float> input;
        (*is) >> input;
        _map.insert(input);
    } while( is->peek( ) != EOF );

    ostream *os = &cout;
    multimap<string,float>::iterator mit = _map.begin( );
    float sum = 0.0;
    while( mit != _map.end( ) ) {
        pair<string,float> p_pair = (*mit);
        (*os) << p_pair;
        sum+=p_pair.second;
        mit++;
    }
    float mean = static_cast<float>( sum/_map.size( ) );
    (*os) << "Sum: " << sum << " Mean: " << mean << endl;
}


texts: Check if list contains a pair which adds up to a given sum

texts:
Kindly review this scala code for given problem and suggest improvements.

Problem - Given an array of integers and a target sum, check if array contains a pair which adds up to sum.

Example -

i/p - (1,2,4,5,6) 7
o/p - true

i/p - (1,1,1,5,6) 2
o/p - true

i/p - (1,4,4,5,6) 13
o/p - false

Scala implementation

import scala.collection.immutable._

object FindMatchingSum {
  def containsMatchingSum(data: Array[Int], complementTable: Set[Int], sum: Int): Boolean = {
    if (data.isEmpty) false
    else if (complementTable contains data.head) true
    else containsMatchingSum(data.drop(1), complementTable ++ Set(sum-data.head), sum)
  }

  def main(args: Array[String]):Unit = {
    println(containsMatchingSum(Array(1,2,4,5,6), Set[Int](), 7))
    println(containsMatchingSum(Array(1,1,1,5,6), Set[Int](), 2))
    println(containsMatchingSum(Array(1,4,4,5,6), Set[Int](), 9))
    println(containsMatchingSum(Array(1,4,4,5,6), Set[Int](), 13))
  }
}

Sample run

scalac FindMatchingSum.scala
scala FindMatchingSum
true
true
true
false


texts: AJAX alternative of using jQuery form UI

texts:
I was using the jQuery form plugin to process form submission (found here) on my page but now have to switch to using an purely jQuery AJAX based method (without using any the form plugin but I can use jQuery). What would be the best method of achieving this? I'm having difficulty translating it across. What would an ideal solution look like?

// prepare the form when the DOM is ready

$(document).ready(function() {
var options = {
    target:        '#result',
    beforeSubmit:  showRequest,
    success:       showResponse
};

// bind to the form's submit event

$('#booking').submit(function() {
    $(this).ajaxSubmit(options);
    return false;
    });
});

// pre-submit callback

function showRequest(formData, jqForm, options) {
    var queryString = $.param(formData);
    // alert('About to submit: \n\n' + queryString);
}

// post-submit callback

function showResponse(responseText, statusText, xhr, $form)  {
    $('#last-step').fadeOut(300, function() {
    $('#result').html(responseText).fadeIn(300);
    });
}


texts:
This code basically connects to a database, sets login success and failure pages, queries the database for user details, checks if user is active, sets session value and redirects accordingly.

Can you have a look? What do you think of it? Any suggestions?

<?php

session_start();

// Connect to the database
try {
    $db = new PDO('mysql:host=localhost; dbname=database', 'username', 'password');
    $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    $db->exec("SET NAMES 'utf8'");
} catch(Exception $e) {
    exit;
}

// Set URL for successful login and unsuccessful login
if($_POST['page']) {
    $success = $_POST['page'];
} else {
    $success = 'http://website.com/members';
}
$fail = 'http://website.com/login';

// Check if login came from my server
if($_SERVER['SERVER_NAME'] != 'website.com') {
    header('Location: ' . $fail);
}

// Check if a user is trying to login
if($_POST) {

    // Query the users details
    try {
        $user_query = $db->prepare('SELECT * FROM users LEFT JOIN zones ON user_timezone = zone_id WHERE user_email = ? AND user_pass = ?');
        $user_query->bindParam(1, $_POST['username'], PDO::PARAM_STR, 50);
        $user_query->bindParam(2, $_POST['password'], PDO::PARAM_STR, 15);
        $user = $user_query->execute();
        $user = $user_query->fetch(PDO::FETCH_ASSOC);
    } catch(Exception $e) {
        exit;
    }

    // Make sure account is active
    if($user['user_active'] != 1) {
        header('Location: ' . $fail . '?error=2');
        exit;
    }

    // Make sure user exists
    if($user != FALSE) {
        $_SESSION['uid'] = $user['user_id'];
        $_SESSION['utz'] = $user['zone_name'];
        header('Location: ' . $success);
    } else {
        header('Location: ' . $fail . '?error=1');
        exit;
    }
} else {
    header('Location: ' . $fail . '?error=4');
    exit;
}

?>


texts: Program to find the mean, median, and mode of numbers

texts:
I was attempting to build a program using Ruby that asks the user to input at least three numbers, and it returns the mean, median, and mode of those numbers.

A developer friend of mine glanced over it and said that the program was wrong, but didn't state specifically what was wrong with it. I have looked over it and tested it repeatedly and can't figure out what's wrong with it.

puts "Please input three or more numbers with spaces inbetween them:"
numbers = gets.chomp
numbers = numbers.split(" ").map(&:to_i)
length = numbers.length
y = 0.000
numbers.each do |x|
    y = x + y
end
mean = y / length
print "Mean: #{mean}"
print "\n"
a_order = numbers.sort
length1 = (length - 1) / 2
if length%2 == 1
    median = a_order[length1]
else
    length2 = length1 + 1
    median = (a_order[length1] + a_order[length2]) / 2.000
end
print "Median: #{median}"
print "\n"
frequencies = Hash.new(0)
numbers.each do |number|
    frequencies[number] = frequencies[number] + 1
end
frequencies = frequencies.sort_by { |a, b| b }
frequencies.reverse!
frequencies = frequencies.to_a
if frequencies[0][1] == frequencies[1][1]
    print "Mode: invalid"
else
    print "Mode: #{frequencies[0][0]}"
end


texts: What is the best way to get the child class name for use in a parent class

texts:
I am currently trying to implement a very simple MVC framework as a way of helping me understand how they work. My base controller class has 2 properties, a model and a view. All controllers have a generic view class property however only certain controllers have a model.

I needed a way of obtaining the name of the child controller class in the base controller class so that in the constructor I can check to see if a model class exists and instantiate one if so. I think I have come up with a solution using late static binding. I do not fully understand the concept, but as far as I can tell, if used in a parent class the static keyword refers to the child class.

I also implemented a function className() in the controller class which uses the 'this' keyword to get the name of the current class. This function is then called with the static keyword resulting in the name of the child class being obtained.

Below is the code for the Controller class. All models are titled controllerName_model.

/**
* Base controller class, creates a generic view class and a model class (if one exists for the child class) for the controller.
*/
class Controller
{
    public $view;
    public $model;

    public function __construct()
    {
        //Create a new genereic view object
        $this->view = new View();

        //Use late static binding to get the name of the child class extending this base class
        $name = static::className();
        //Create the path to the related model (if it exists)
        $path = 'models/' . $name . '_model.php';

        //If the model exists then require the file and create a new model object and store in $this->model
        if(file_exists($path)) {
            require $path;

            $modelName = $name . '_Model';
            $this->model = new $modelName();
        }
    }

    /**
    * This class returns the name of each class that extends this base controller class. It is used in the
    * constructor with late static binding to get the name of the child class so that a model can be created if one exists.
    */
    public function className() {
        return get_class($this);
    }
}

As far as I can tell this method is working but I am not confident that it is correct or that it is the best way of doing this. If anyone knows of any other ways of doing this or can point out any flaws in this approach I would be extremely grateful. Thanks.


texts: Append string to list items based on function arguments

texts:
My goal with this function is to append a string to a list that's being manipulated first, then return the manipulated string. This all happens with a bit of logic in-between, making me loop  through the array 3 times, which I'd like to change to a cleaner approach:

function getNiceTags( $post )
{
    $output         = '
';
    $tags_list      = [];

    $tags = get_the_tags($post->ID);

    if( !isset( $tags ) ) {
        return;
    }

    foreach ($tags as $tag) {
        $tags_list[] = $tag->name;
    }

    if( isset( $args['additional-text'] ) ) {
        foreach( $tags_list as $tag ) {
            $tag_temp .= sprintf(
                /* translators: %s: post tag. */
                esc_html_x( $args['additional-text'] . '%s', 'post tags', '_s' ),
                $tag
            );

            $output .= '
' . $tag_temp . '
';
            unset( $tag_temp );
        }
    } else {
        foreach( $tags_list as $tag ) {
            $tag_temp .= sprintf(
                /* translators: %s: post tag. */
                esc_html_x('%s', 'post tags', '_s'),
                $tag
            );

            $output .= '
' . $tag_temp . '
';
            unset($tag_temp);
        }
    }

    $output .= '
';

    return $output;
}

The $tags = get_the_tags($post->ID); generates an array of tags from a certain post.

$args['additional-text'] will be the main operator for my logic. If this function gets a this $args['additional-text'] string in its arguments, then it should append that string to my list of tags, if not, then it should just return my tags.

How can I improve this?


texts:
The entire flow depends on parameters. It's all in the same method with an if/else, but I want to make the code a bit more clear. How can I functionally decompose this method into many?

private void BindTreeView(IEnumerable<Opcion> OptionList, TreeNode parentNode)
{
    var nodes = OptionList.Where(x => parentNode == null ? x.ParentID == 0 : x.ParentID == int.Parse(parentNode.Value));

    if (_pagemode != BoPage.PageMode.View)
    {
        foreach (Opcion node in nodes)
        {
            TreeNode newNode = new TreeNode();
            newNode.Text = (node.ParentID == 0) ? string.Format(@"{1}", node.OpcionID.ToString(), node.Descripcion.ToString()) : string.Format(@"{1}", node.ParentID.ToString(), node.Descripcion.ToString());
            newNode.Value = node.OpcionID.ToString();
            newNode.ToolTip = node.Descripcion.ToString();

            if (parentNode == null)
            {
                TreeViewPalabrasClaveOpciones.Nodes.Add(newNode);
            }
            else
            {
                if (node.PalabrasClaveOpciones.Where(c => c.KeywordID == _idKeyWord).Count() > 0)
                {
                    newNode.Checked = true;
                    parentNode.Expand();
                }
                parentNode.ChildNodes.Add(newNode);
            }
            BindTreeView(OptionList, newNode);
        }

    }
    else
    {
        foreach (Opcion node in nodes)
        {
            if (ExistKeyWord(node))
            {
                TreeNode newNode = new TreeNode();
                newNode.Text = (node.ParentID == 0) ? string.Format(@"{1}", node.OpcionID.ToString(), node.Descripcion.ToString()) : string.Format(@"{1}", node.ParentID.ToString(), node.Descripcion.ToString());
                newNode.Value = node.OpcionID.ToString();
                newNode.ToolTip = node.Descripcion.ToString();

                if (parentNode == null )
                {
                    TreeViewPalabrasClaveOpciones.Nodes.Add(newNode);
                }
                else
                {
                    if (node.PalabrasClaveOpciones.Where(c => c.KeywordID == _idKeyWord).Count() > 0)
                    {
                        newNode.Checked = true;
                        parentNode.Expand();
                    }

                    if (node.PalabrasClaveOpciones.Where(c => c.KeywordID == _idKeyWord).Count() > 0)
                    {
                        parentNode.ChildNodes.Add(newNode);
                    }

                }
                BindTreeView(OptionList, newNode);
            }
        }

    }

}


texts: Unquoting booleans, numbers, etc. in a JSON string

texts:
I have a method that takes a JSON string as input and "fixes" it. By that, I mean, that the JSON string comes in with all values quoted. My method un-quotes the values that shouldn't be quoted (i.e. true, false, numbers, {}, etc). The method was originally doing it by doing 4 string replaces (for the true / false, etc) and regex replace for the numbers. Kind of slow. So I re-wrote it with StringBuilder:

    protected static string FixupJson(string json)
    {
        if (json == null)
            throw new ArgumentNullException(nameof(json));

        int nLen = json.Length;

        StringBuilder sb = new StringBuilder(nLen);

        for (int i = 0; i < nLen; i++)
        {
            char ch = json[i];

            if (ch == ':' && json[i+1] == ' ' && json[i + 2] == '\"')
            {
                int k = json.IndexOf('\"', i + 3);

                sb.Append(": ");

                string g = json.Substring(i + 3, k - i - 3);

                bool bQuote = true;

                if (g == "true" || g == "false" || g == "null" || g == "{}")
                    bQuote = false;
                else if (g == "NaN")
                    bQuote = true;
                else if (Double.TryParse(g, out double d))
                    bQuote = false;

                if (bQuote)
                    sb.Append('\"');

                sb.Append(g);

                if (bQuote)
                    sb.Append('\"');

                i = k;
            }
            else
            {
                sb.Append(ch);
            }
        }

        return sb.ToString();
    }

This got me a 35% improvement, but I want to see if there is a better approach or if I can get this faster. My first StringBuilder approach, instead of appending char by char would append chunks pulled out with SubString(). That was actually a lot slower then this version.

Yes, I understand the right way to do it would be to fix it at the source :), which I do control, but the way the json gets serialized out at the source, I don't know if the value needs to be quoted until the json is fully spit out (or at least until the value is fully spit out) as a single value can be a formatted string from multiple sources (i.e. "myVal": "(this part from one place)|(this part from another place))". So "fixing it there" would mean going from a single String.Format() for the entire json to a bunch of them for each value. Right now the JSON is "pre-rendered" (once) and passed into a String.Format() to fill in the values, so by fixing it there I'd have to go to a bunch of little String.Format()'s to format each value then pass it in to the big String.Format()… so I figure this is a decent compromise.

EDIT: Should handle any old json, but this was the one I was using in my test app in C# string format ready to paste :).

"{\r\n  \"xxx\": \"TRACE|1\",\r\n  \"Timestamp\": \"2019-01-01 12:44:36.529\",\r\n  \"Message\": {\r\n    \"a\": \"bbb\",\r\n    \"b1\": {\r\n      \"b2\": \"test2\",\r\n      \"b3\": \"Test1\",\r\n      \"b4\": \"true\",\r\n      \"b5\": \"178\"\r\n    }\r\n  },\r\n  \"ThreadId\": \"1\",\r\n  \"Exception\": \"{}\"\r\n}"


texts:
I am extending a matrix with some calculated values.  This code runs very slowly.

Is there a way to vectorize this with slice and hstack?

import numpy as np

def expand(X):
    X_expanded = np.zeros((X.shape[0], 6))
    for i in range(X.shape[0]):
        X_expanded[i,0]=X[i,0]
        X_expanded[i,1]=X[i,1]
        X_expanded[i,2]=X[i,0]**2
        X_expanded[i,3]=X[i,1]**2
        X_expanded[i,4]=X[i,0]*X[i,1]
        X_expanded[i,5]=1
    return X_expanded