texts:
I'm trying to solve this challenge, which consists of finding the next biggest number formed by the digits of the passed in number. If it is impossible to find a number larger than the passed in parameter by rearranging the digits, return -1.

EX: nextBigger(12) === 21
    nextBigger(2017) === 2071
    nextBigger(987654321) === -1

My solution works, but they are testing a bunch of really long numbers that are causing it to time out. I don't even get to see what these really long numbers are because it times out and doesn't return any test cases. I was wondering what could be done to optimize this further.

function nextBigger(n){

      let numString = n.toString();
      let permutations = []
      let smallest = numString[0];
      let descending = true;
      let same = true;

      for(let i = 1; i < numString.length;i++){
        if(numString[i-1] < numString[i]){
            descending = false;
        }
        if(numString[i-1] != numString[i]){
            same = false;
        }

        if(smallest > numString[i]){
          smallest = numString[i]
        }
      }
      if(descending || same){
        return -1;
      }

      const permute = (prefix, str) => {
        let index = String(str).length;
        if(index == 1){
          permutations.push( prefix + str );
        }

        for(let i = 0; i < index; i++){
          permute(prefix + str[i], str.slice(0,i) + str.slice(i+1,index))
        }
      }

      let nextBiggest = Infinity;
      for(let i = numString.length - 2; i >= 0; i--){
          let start = numString.slice(0,i);
          let end = numString.slice(i,numString.length)
          permute(start,end)
          for(let j = 0; j < permutations.length; j++){
            if(permutations[j] > n && permutations[j] < nextBiggest){
              nextBiggest = permutations[j];
            }
          }
          if(smallest == numString[i]){
            return nextBiggest
          }
          permutations = [];
      }
      return -1
    }

    console.log(nextBigger(28554))
    //42558
    console.log(nextBigger(1961821))
    //1962118
    console.log(nextBigger(12))
    //21
    console.log(nextBigger(1111))
    //-1
    console.log(nextBigger(987654321))
    //-1


texts: Sorting lists by various measures of goodness

texts:
def sort[A, B: Ordering](data: List[A], desc: Boolean)(measure: A => B): List[A] = {
        val baseOrdering = Ordering.by(measure)
        val ordering = if (desc) baseOrdering.reverse else baseOrdering
        data.sorted(ordering)
    }

  private def sortOne(stats: List[One], by: String, desc: Boolean): List[One] =
    by match {
      case "good" => sort(stats, desc)(_.data.good)
      case "bad" => sort(stats, desc)(_.data.bad)
      case "gross" => sort(stats, desc)(_.data.gross)
      case "warn" => sort(stats, desc)(_.data.warn)
      case "exuberant" => sort(stats, desc)(_.data.exuberant)
      case other => stats
    }
  private def sortTwo(stats: List[Two], by: String, desc: Boolean): List[Two] =
    by match {
      case "good" => sort(stats, desc)(_.data.good)
      case "bad" => sort(stats, desc)(_.data.bad)
      case "gross" => sort(stats, desc)(_.data.gross)
      case "warn" => sort(stats, desc)(_.data.warn)
      case "exuberant" => sort(stats, desc)(_.data.exuberant)
      case other => stats
    }

  private def sortThird(stats: List[Third], by: String, desc: Boolean): List[Third] =
    by match {
      case "good" => sort(stats, desc)(_.data.good)
      case "bad" => sort(stats, desc)(_.data.bad)
      case "gross" => sort(stats, desc)(_.data.gross)
      case "warn" => sort(stats, desc)(_.data.warn)
      case "exuberant" => sort(stats, desc)(_.data.exuberant)
      case other => stats
    }

Actually there are more classes. They all have same fields like good, gross, bad, warn.

These classes that are in methods have all similar fields good, gross, bad, warn. I can't rewrite classes.

It is working, but it looks bad. Maybe someone has some ideas?


texts: Including references in onResume Lifecycle

texts:
What's a more concise way to do this? It's way too verbose for my taste.

    @Override
    protected void onResume() {
    super.onResume();
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY - 1);
    TinyDB tinydb = new TinyDB(this);
    Log.v(TAG + "BaseStartup.onResume", "onResume");
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("tv.apps.v4.ve");
    intentFilter.addAction("tv.apps.v4.ev");
    intentFilter.addAction("tv.apps.v4.we");
    intentFilter.addAction("tv.apps.v4.wef");
    intentFilter.addAction("tv.apps.v4.wefew");
    intentFilter.addAction("tv.apps.v4.gwe");
    intentFilter.addAction("tv.apps.v4.ewew");
    intentFilter.addAction("SMS_ewe");
    intentFilter.addAction("INTERNET_BACK_UPweeew");
    intentFilter.addAction("tv.apps.v4.weewwee");
    intentFilter.addAction("tv.apps.weewe");
    intentFilter.addAction("tv.apps.weet");
    intentFilter.addAction("tv.apps.weewewewees");
   // Get source of open for app re-engagement
    mobileAppTracker.setReferralSources(this);
    // MAT will not function unless the measureSession call is included
    mobileAppTracker.measureSession();
    //sceneTransport("resumeSession", "null", "null" );

}


texts: Questionnaire program using many wxPython windows

texts:
I have over 300 questions that I plan to include in the program. The flow is pretty much like this:

Create a window with the question
Store answer in variable
Create NEW window with question
Store NEW answer

(This continues on for over 300 questions.)

I have 2 questions:

Will this eventually lead to a crash since I'm creating so many windows?
Everything works with this code if you select 'Yes' to the second question (A2) but it does not work if you select 'No'. Can you please see if you can find what's wrong with it?

import wx

a1 = ['Apples', 'Bananas', 'Strawberries', 'Watermelon',
     "Don't remember", 'None of the above']

a2 = ['No', 'Yes']

a4 = ['No', 'Yes']

class Fruit(wx.Frame):

    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, 'Fruit', size=(300,200))

        #create panel and button
        panel = wx.Panel(self)

        # B1 - create multiple choice list
        box = wx.MultiChoiceDialog(None, """

A1.    What kind of fruit did you buy at the store?""", 'Fruit', a1)
        if box.ShowModal() == wx.ID_OK:
            a_1 = box.GetSelections()

        print (a_1, '\n')

        # A2 - create single choice list
        box = wx.SingleChoiceDialog(None, """
A2.    Do you like eating fruit?
""", 'Fruit', a2)
        if box.ShowModal() == wx.ID_OK:
            a_2 = box.GetStringSelection()

        print (a_2, '\n')

        if a_2 == 'Yes':
            box = wx.TextEntryDialog(None, "A3.    What kind of fruit is your favorite? ", "Fruit", "")
        if box.ShowModal() == wx.ID_OK:
            a_3 = box.GetValue()

        print (a_3, '\n')

        box = wx.SingleChoiceDialog(None, """
A4.    Did you eat the fruit that you bought?
""", 'Fruit', a4)
        if box.ShowModal() == wx.ID_OK:
            a_4 = box.GetStringSelection()

        print (a_4, '\n')


texts:
This might be a loaded question, but here goes.  I have some code that is very similar between all the methods.  I am trying to find a way to accomplish all methods with a generic method/function. I'm not sure if I should be using delegates, and if so how to implement in this specific situation, or if there is a much more simple way to make a generic method.

Below I have copied the code I am trying to make generic.  All methods take this basic syntax: (Parameters) ConcurrentQueue(pPeople),  With that collection, the first part gets the count of the records.  Each method iterates over a different part of the collection (or collection in the collection).

Thanks for any help or nudges in the right direction!  If you have an idea that would help, it would be great if you could give an example related to this code (or very similar).

Code:  I have copied three methods that give that show similar code (there are many more).

    private void UpdatepPeopleAddressIDs(ConcurrentQueue<pPeople> people)
    {
        //Get Count of records that need an ID from uMaxIDs
        int updateCount = 0; object lockObject = new object();
        Parallel.ForEach<pPeople>(people, person =>
        {
            person.myPeopleAddressList.ForEach(address =>
            {
                if (address.ID == 0)
                {
                    lock (lockObject)
                    {
                        updateCount++;
                    }
                }
            });
        });
    }

    private void UpdatepPeopleContactNumbersIDs(ConcurrentQueue<pPeople> people)
    {
        //Get Count of records that need an ID from uMaxIDs
        int updateCount = 0; object lockObject = new object();
        Parallel.ForEach<pPeople>(people, person =>
        {
            person.myPeopleContactsList.ForEach(contact =>
            {
                if (contact.ID == 0)
                {
                    lock (lockObject)
                    {
                        updateCount++;
                    }
                }
            });
        });
    }

    private void UpdatepPeopleEmailIDs(ConcurrentQueue<pPeople> people)
    {
        //Get Count of records that need an ID from uMaxIDs
        int updateCount = 0; object lockObject = new object();
        Parallel.ForEach<pPeople>(people, person =>
        {
            person.myPeopleEmailsList.ForEach(emails =>
            {
                if (emails.ID == 0)
                {
                    lock (lockObject)
                    {
                        updateCount++;
                    }
                }
            });
        });
    }


texts:
Basing my work on a JavaScript progress bar created by another person, I added an animated percentage count.  This solution is really ugly but it works.

I don't know how to avoid having to declare the percentage value twice in the HTML.  I would also like to unify the parts of the code responsible for the progress bar and the percentage counter.

// This part of the code is responsible for loading progress bar:

$('.progressbar').each(function() {
    $(this).find('.progressbar-bar').width(0);
});

$('.progressbar').each(function() {

    $(this).find('.progressbar-bar').animate({
        width: $(this).attr('data-percent')
    }, 2000);
});

// Part of the code responsible for loading percentages:

$('.progress-bar-percent[data-percentage]').each(function () {

        var progress = $(this);
        var percentage = Math.ceil($(this).attr('data-percentage'));

            $({countNum: 0}).animate({countNum: percentage}, {
                duration: 2000,
                easing:'linear',
                step: function() {
                // What todo on every count
                    var pct = '';
                    if(percentage == 0){
                        pct = Math.floor(this.countNum) + '%';
                    }else{
                        pct = Math.floor(this.countNum+1) + '%';
                    }
                    progress.text(pct);
                }
            });
    });

Something


texts: Merge objects in Kotlin if they are updated

texts:
I am very new to Kotlin and I am trying to achieve this:

I get a batch of PersonDetails to save or update
In the batch, the same PersonDetails with name is different locale can be present.
The end goal of this method is to merge the batch itself and also merge the existing entries in Database then return the updated data structure for saving into DB.

I am not very happy with the way I have coded, can you please review this code and give your review comments.

fun doProcess(batchToProcess: List<PersonDetail>) : Map<Long, PersonDetail> {
    val idsInBatch = batchToProcess.map { it.lcmId }.toList()
    val personDetailsFromDb = personDetailsRepository.getBatch(idsInBatch)
        .map { it.lcmId to it }
        .toMap()

    val batchesOfPersonDetails = mutableMapOf<Long, PersonDetail>()

    batchToProcess.map { aPerson ->
        var personDetail = batchesOfPersonDetails[aPerson.lcmId]
        if (personDetail == null) {
            personDetail = personDetailsFromDb[aPerson.lcmId]
        }

        val updatedPersonDetail = when {
            personDetail == null -> aPerson.toPersonDetail()

            personDetail.isActive != aPerson.isActive -> {
                personDetail.isActive = personDetail.isActive
                personDetail
            }

            personDetail.localeDetails[aPerson.localeCode] != aPerson.localeName -> {
                personDetail.localeDetails[aPerson.localeCode] = aPerson.localeName
                personDetail
            }

            else -> {
                logger.info { "Duplicate_Event for id ${aPerson.lcmId}" }
                personDetail
            }
        }

        batchesOfPersonDetails[updatedPersonDetail.lcmId] = updatedPersonDetail
    }

    return batchesOfPersonDetails
}


texts:
I am looking for people's opinions on my use of a set of non standard "standard classes". Basically I am working on a 'modern' C++ Lexical Analyser and Parser Generator duo to replace flex and GNU Bison which will work as a library and tool combination.

I have a number of non standard extensions of std library classes. The reason I am needing these nonstandard classes is to be able to express algorithms more succinctly and nearer the mathematical equivalents.

Here's a vector class that allows extension via operator[], which also has a generic Base parameter, allowing the vector to be based at 1 rather than zero, for example. And I return indices as size_t's rather than iterators as indexes are more useful in a traditional mathematical sense.

//
//  vector.h - auto sizing 'vector' class
//
//  Copyright (c) 2015-2016 Aaron Nathaniel Gray under the MIT License
//

#include <vector>
#include <iostream>

template<typename T, size_t Base = 0>
class vector : public std::vector<T> {
public:
    vector() : std::vector<T>() {}
    vector(const std::initializer_list<T> il) : std::vector<T>(il) {}
    ~vector() {}

    iterator last() { return end() - 1; }
    const_iterator clast() const { return end - 1; }

    size_t size() const { return std::vector<T>::size(); }
    void resize(size_t _size) { std::vector<T>::resize(_size); }
    T& operator [] (size_t index) {
        if (index + 1 - Base > size())
            resize(index + 1 - Base);
        return std::vector<T>::operator[](index - Base);
    }
    const T operator [] (size_t index) const {
        if (index + 1 - Base <= size())
            return std::vector<T>::operator[](index - Base);
        else
            return T();
    }
    signed find(const T& value) {
        auto i = std::find(cbegin(), cend(), value);
        if (i != cend())
            return i - cbegin() + Base;
        else
            return -1;
    }
    size_t add(const T value = T()) {
        push_back(value);
        return size() - 1 + Base;
    }
    std::string toString() const;
};

template<typename T, size_t Base = 0>
std::string vector<T, Base>::toString() const {
    std::stringstream ss;

    for (size_t element = Base; element < size() + Base; ++element) {
        ss << (*this)[element];
        if (element < size() + Base)
            ss << ",";
        ss << std::endl;
    }

    return ss.str();
}

I am wondering whether to use the namespace nonstd::vector.

I also have non-standard set, deque, and a very extensive bitset class.

Example:

nonstd::vector<size_t> accept;

for(auto state : states) {

    .... accept = ....

    this->accept[state->index] = accept;
}

Here, state->index may not be sequential or contiguous and maximum value not known, so push_back will not work.

And a find example:

nonstd::vector<Production*> productions;

...

size_t productionIndex = production.find(aProduction);


texts: Randomly re-partition 1Dimensional List to 2Dimensional

texts:
I wrote a solution Please look at the my approach is correct? There is a better solution?

List<Tuple<object, object, object>> OneDimensionalLists = new List<Tuple<object, object, object>>();
List<Tuple<object, object, object>[]> TwoDimensionalLists = new List<Tuple<object, object, object>[]>();

int i1 = 0;
for (int i = 0; i < OneDimensionalLists.Count; i++)
{
    var random = new Random(seed);
    int next = random.Next(10, 30);
    TwoDimensionalLists.Add(new Tuple<object, object, object>[next]);
    for (int j = 0; j < next; j++)
    {
        if (OneDimensionalLists.Count == i1)
            goto go;

        TwoDimensionalLists[i][j] = OneDimensionalLists[i1++];
    }
}
go:


texts:
I am looking to have a code review on this tiny repository.

The code seems to work, but I am not sure if I have written it in idiomatic Rust.

#[derive(Debug)]
pub struct QuickFind {
    items: Vec<u64>,
}

impl QuickFind {
    pub fn new(length: u64) -> QuickFind {
        let mut result: QuickFind = QuickFind { items: Vec::new() };

        for i in 0..length {
            result.items.push(i);
        }

        result
    }

    pub fn union(&mut self, left_index: u64, right_index: u64) {
        let left_group_id = self.items[left_index as usize];

        self.items[right_index as usize] = left_group_id;
    }

    pub fn get_items(&self) -> &[u64] {
        &self.items
    }

    pub fn is_connected(&self, left_index: u64, right_index: u64) -> bool {
        self.items[left_index as usize] == self.items[right_index as usize]
    }
}


texts:
I enjoy making silly programs every once in a while. This is one of them. It makes nice sounding notes that vary slightly depending on the key being entered into a TextArea. When you press enter, it plays back all the notes you have entered. That's pretty much all it does. I'm looking for constructive criticism regarding the coding style, and perhaps usability.

package boop;

import java.awt.TextArea;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashMap;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.swing.JFrame;

public class Boop extends JFrame implements KeyListener {
    private final TextArea textArea;

    private class Noise implements Runnable {

        private int noise[];
        public boolean sound = true;
        private final int freq;
        private int ms = 100;
        private int samples = (int) ((ms * SAMPLE_RATE) / 1000);
        private byte[] output = new byte[samples];
        private int i = 0;
        private double period;

        public Noise(int freq) {
            this.freq = freq;
            period = (double) SAMPLE_RATE / freq;
            new Thread(this).start();
        }

        @Override
        public void run() {
            SourceDataLine line;
            try {
                line = AudioSystem.getSourceDataLine(af);
                line.open(af, SAMPLE_RATE);
            } catch (LineUnavailableException ex) {
                ex.printStackTrace();
                return;
            }
            line.start();
            while (i < output.length) {
                double angle = 2.0 * Math.PI * i / period * 1.0 + 0.08;
                output[i++] += (byte) (Math.sin(angle) * 127f);
            }
            while (sound) {
                line.write(output, 0, output.length);
            }
            line.close();
        }
    }

    private class Reader implements Runnable {
        private final String sz;
        Reader(String s) {
            sz = s;
            new Thread(this).start();
        }
        public void run() {
            Noise n;
            for (char c: sz.toCharArray()) {
                n = new Noise(c % 20 * 110);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                    continue;
                }
                n.sound = false;
            }
        }
    }

    private static final int SAMPLE_RATE = 16 * 1024;
    private final AudioFormat af =
            new AudioFormat(SAMPLE_RATE, 8, 1, true, true);
    private HashMap<Character, Noise> noises;

    public static void main(String[] args) {
        new Boop();
    }

    public Boop()  {
        noises = new HashMap<>();
        textArea = new TextArea(20, 80);
        textArea.addKeyListener(this);
        add(textArea);
        pack();
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    @Override
    public void keyTyped(KeyEvent ke) {
        try {
            keyReleased(ke);
        } finally {
            char ch = ke.getKeyChar();
            Noise t = new Noise(ch % 20 * 110);
            noises.put(ch, t);
        }
    }

    @Override
    public void keyPressed(KeyEvent ke) {
        if (ke.getKeyCode() == KeyEvent.VK_ENTER)
            new Reader(textArea.getText().toString());
    }

    @Override
    public void keyReleased(KeyEvent ke) {
        try {
            noises.get(ke.getKeyChar()).sound = false;
        } finally {
            return;
        }
    }
}


texts:
Is there a way to rewrite this code to make it more laconic? I'm using Java 6.

Object value = methodOutOfMyControl();
Collection<LinkedHashSet<String>> values = ((Map) value).values();
Set<String> strings = new HashSet<String>();
for (LinkedHashSet<String> set : values) {
    strings.addAll(set);
}


texts:
$controller = new UserController();

if (isset($_POST['submitform']))
{
    $validated = false;

    $inputs = array (
        'username', 'email', 'password',
        'repassword', 'password_f', 'repassword_f',
        'display'
    );

    $i = 0;

    foreach ($inputs as $key)
    {
        if (isset($_POST[$key]) && !empty($_POST[$key]))
        {
            $i++;
            if ((int)$i == count($inputs))
            {
                $validated = true;
                break;
            }
            else
            {
                $controller->error = "";
                break;
            }
        }
    }

    if ($validated)
    {
        echo 2;
    }
}

So let's overview the code.

First we are checking if the form was submitted.

Then we are creating a new boolean $validated and setting it false by default.

Then we created our array with the POST names.

Now the checking part, setting variable int i to 0 by default.
Now we are looping through the array elements.

Checking if the current index was set or not empty, if yes, add +1 to int $i.

Once int $i hits the number of counted elements of our array, set $validated to true, and break out of the array, else parse error and break out.

Then we are checking, if bool $validated is true, then echo 2.

Is it a good way of doing this? Is there any cleaner/better way?


texts: Running a master query and a query of queries

texts:
The following is code I'm running to FIRST, SECOND, THIRD and so on until SEVENTH with a master query and a query of query.

As it's clear that I'm using the master query for each of FIRSTCONN, SECONDCONN etc., I want to have only one master query and the rest subqueries.

Is this an efficient way to do so?
How can I make my code efficient?

<!--- QoQ for FIRSTCONN --->
<!--- Master Query --->
<cfquery datasource = "XX.XX.X.XX" name="master1">
SELECT DATE(Timedetail) as FIRSTCONN, COUNT(Timedetail) as FIRSTOccurances, EVENTS
FROM  MyDatabase
WHERE EVENTS = "FIRST"
GROUP BY FIRSTCONN ;
</cfquery>

<!--- Detail Query --->
<!--- <cfdump var = "#master#"> --->
<cfquery dbtype="query" name="detail1">
SELECT  *
FROM master1
WHERE FIRSTCONN  >= <cfqueryparam value="#form.startdate#" cfsqltype="cf_sql_varchar">
AND FIRSTCONN  <  <cfqueryparam value="#dateAdd('d', 1,form.enddate)#" cfsqltype="cf_sql_varchar">;
</cfquery>

<!--- QoQ for SECONDCONN --->
<!--- Master Query --->
<cfquery datasource = "XX.XX.X.XX" name="master2">
SELECT DATE(Timedetail) as SECONDCONN, COUNT(Timedetail) as SECONDOccurances, EVENTS
FROM  MyDatabase
WHERE EVENTS = "SECOND"
GROUP BY SECONDCONN ;
</cfquery>

<!--- Detail Query --->
<!--- <cfdump var = "#master#"> --->
<cfquery dbtype="query" name="detail2">
SELECT  *
FROM   master2
WHERE  SECONDCONN  >= <cfqueryparam value="#form.startdate#" cfsqltype="cf_sql_varchar">
AND    SECONDCONN  <  <cfqueryparam value="#dateAdd('d', 1,form.enddate)#" cfsqltype="cf_sql_varchar">;
</cfquery>


texts:
I created a post carousel (it's being used on a WordPress theme initially), but I've adapted it to just HTML/CSS/JS one.

CodePen

var $carousel = $('.post_excerpt_carousel');

$carousel.each(function(){

    var $this = $(this);

    var outer_width = $(window).outerWidth();
    var container_width;

    if (outer_width > 1145) {
        container_width = 1170;
    }

    if (outer_width > 960 && outer_width < 1145) {
        container_width = 960;
    }

    if (outer_width < 960) {
        container_width = parseInt((9/10)*outer_width,10);
    }

    var duration = $this.data('duration');
    var li_number = $this.find('li').length;
    var $ul = $this.find('ul');
    var $li = $ul.find('li');
    $li.removeClass('active');

    if (outer_width < 760){
        $li.css('width', container_width);
        $li.eq(1).addClass('active');
        if ($li.eq(2).hasClass('active')) {
            $li.eq(2).removeClass('active');
        }
    } else if (outer_width > 760){
        $li.eq(1).addClass('active');
        $li.eq(2).addClass('active');
    }

    var list_width = $this.find('li').outerWidth(true);
    var left_offset;

    left_offset = parseInt(list_width - (outer_width - container_width-42)/2, 10);

    $ul.css({'display': 'inline-block', 'width': li_number * $this.find('li').outerWidth(true) + 'px', 'left': -left_offset + 'px'});

    var not_active_no = $this.find('li').not('.first').not('.last').not('.active').length;
    var not_active_width = not_active_no * $this.find('li').outerWidth(true);

    $this.on('click', '.carousel_next', function (e) {
        e.preventDefault();

        if($this.find('li.last').prev().hasClass('active')){
            return;
        } else {
            var $a = $('.active', $this);

            if (!$a.next().hasClass('last') && !$ul.is(':animated')) {
                $a.removeClass('active').next().addClass('active');
            }

            if (!$ul.is(':animated')) {
                $ul.animate({
                    left: parseInt($ul.css('left'), 10) - $ul.find('li').outerWidth(true),
                }, duration);
            }
        }

    });

    $this.on('click', '.carousel_prev', function (e) {
        e.preventDefault();

        if($this.find('li.first').next().hasClass('active')){
            return;
        } else {
            var $a = $('.active', $this);

            if (!$a.prev().hasClass('first') && !$ul.is(':animated')) {
                $a.removeClass('active').prev().addClass('active');
            }

            if (!$ul.is(':animated')) {
                $ul.animate({
                    left: parseInt($ul.css('left'), 10) + $ul.find('li').outerWidth(true),
                }, duration);
            }
        }

    });

});


texts:
I have a model class that contains 3 ArrayList which are in order by parallel of the same size. <Object><Calendar><Long> I want to sort it by the <Long> Is this the most clean? is there a better way? This doesn't seem memory efficient.

    public class ResultModel{
        private ArrayList<Object> sets = new ArrayList<Object>();
        private ArrayList<Calendar> dates=new ArrayList<Calendar>();
        private ArrayList<Long> unixtimes=new ArrayList<Long>();
    private class WinningSet implements Comparable<WinningSet>{
            private long unixtime;
            private Object set;
            private Calendar date;
            WinningSet(Object set,Calendar date,long unixtime){
                this.unixtime=unixtime;
                this.set=set;
                this.date=date;
            }
            @Override
            public int compareTo(WinningSet another) {
                return (int) (this.unixtime-another.getUnixtime());
            }
            public long getUnixtime() {
                return unixtime;
            }
            public Object getSet() {
                return set;
            }
            public Calendar getDate() {
                return date;
            }
        }
        public void sortSelf(){
            ArrayList<WinningSet> list=new ArrayList<WinningSet>();
            for(int i=0;i<this.unixtimes.size();i++){
                list.add(new WinningSet(this.sets.get(i),dates.get(i),unixtimes.get(i)));
            }
            Collections.sort(list,Collections.reverseOrder());
            demap(list);
        }
        private void demap(ArrayList<WinningSet> list) {
             ArrayList<Object> tSets = new ArrayList<Object>();
             ArrayList<Calendar> tDates=new ArrayList<Calendar>();
             ArrayList<Long> tUnixtimes=new ArrayList<Long>();
            for(WinningSet temp:list){
                tDates.add(temp.getDate());
                tSets.add(temp.getSet());
                tUnixtimes.add(temp.getUnixtime());
            }
            this.sets=tSets;
            this.dates=tDates;
            this.unixtimes=tUnixtimes;
        }
}


texts: Yet another lightweight Enum for Python 2.7

texts:
I'm trying to develop a lightweight enum for Python 2.7.  This question is downstream of the SO question here; for context, a streamlined version of the bulleted addendum to that question is replicated below:

  My desired feature set is:

  Only having to type the enum name (or value) once in the source definition.
  Valid enum values exposed for IDE autocomplete.
  Enum values stored internally as comprehensible strings.
  Straightforward membership testing using native Python in.
  Ability to import individual enum subclasses via, say, from .enums import myEnum, to avoid cluttering the local namespace with other enums I don't care about.
  I would rather avoid introducing an additional package dependency by using enum34, as I don't (think I) need the feature set.

After reviewing the SO post here on recommendations for non-enum34 implementations of enums in Python 2.7, I also would add:

  Clean, readable definition of enum values.

To note, every form of dynamic namespace construction I've tried, in efforts to accomplish #1, has broken #2.  I'm pretty sure at this point they're mutually exclusive.

In any event, my current solution goes as follows, defining an enum superclass with a metaclassed type with an iterator that returns all members with string content identical to the respective member names:

class SuperEnum(object):
    class __metaclass__(type):
        def __iter__(self):
            for item in self.__dict__:
                if item == self.__dict__[item]:
                    yield item

Each enum is then subclassed from this SuperEnum, e.g.:

class myEnum(SuperEnum):
    this = 'this'
    that = 'that'
    other = 'other'

The usage is working just as I want (except of course for #1), including for the IDE autocomplete of #2:

>>> myEnum.other
'other'
>>> 'this' in myEnum
True
>>> 'thing' in myEnum
False
>>> e = myEnum.other
>>> e in myEnum
True

This construction is far more concise than anything I'd set up around the time I posted the above-linked SO question, so the need to type the value name twice in the enum class definition isn't terribly bothersome.  I'm still interested to know if there's any way to make #1 and #2 play nice together, though.

More generally: what might the weaknesses of this construction be? For my application, performance is of minor concern. There's always the possibility of value collisions, as described here, but using strings as the values dramatically reduces the likelihood.  Security issues? Compatibility problems of some kind?


texts: API to verify whether a Redis entry exists

texts:
I come from a PHP object oriented framework background (Laravel, Symfony, Silex...). With that, validation comes in pre-built classes mechanism in a framework that validates for you parameters that you define and validates against. If it fails validation, you don't proceed.

Example from Laravel:

 public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect('post/create')
                        ->withErrors($validator)
                        ->withInput();
        }

        // Store the blog post...
    }

Here, we define that it is required, max 255 for title. It is easy to read.
Symfony is a bit more elaborate but still easy to read due to easily predefined class:

public static function loadValidatorMetadata(ClassMetadata $metadata)
{
    $metadata->addPropertyConstraint('firstName', new Assert\NotBlank());
    $metadata->addPropertyConstraint(
        'firstName',
        new Assert\Length(array("min" => 3))
    );
}

I'm starting to dive into node.js with express.js as base to create an API (I'm aware that Restify and Loopback exist). Currently I have one end point, which I would like to validate a hash token to identify the client, and then inspect that the stored key/value pair matches. The storage is from redis, the following is the code:

/**
 * Check if the hash is in redis
 * @function CheckParam
 * @param {object} req - json object with the data that will be inserted in queries
 * @param cb - callback
 * @callback {object} status code
 */
http.checkParam = function CheckParam(req, cb) {

    if (typeof req.body.data !== 'undefined' && req.body.data && typeof req.query.hash !== 'undefined'
        && req.query.hash && typeof req.body.id !== 'undefined' && req.body.id) {
        if (typeof req.body.data !== 'object' && typeof req.query.hash !== 'string' && typeof req.body.id !== 'number') {
            log.error({part: 'save'}, 'Wrong parameters type');
            cb(403);
        } else {
            redis.get(req.query.hash, function (err, data) {
                if (err) {
                    log.error({part: 'save'}, 'Error from redis \n ' + err);
                    cb(403);
                } else if (!data) {
                    log.error({part: 'save'}, 'Token not found \n ' + req.query.hash);
                    cb(403);
                } else {
                    try {
                        var obj = JSON.parse(data);
                        if (obj.member.id == req.body.id) {
                            cb(200);
                        } else {
                            log.error({part: 'save'}, 'Wrong user id ' + req.body.id);
                            cb(403);
                        }

                    } catch (e) {
                        log.error({part: 'save'}, 'Error from redis \n ' + e);
                        cb(403);
                    }
                }
            });
        }
    } else {
        log.error({part: 'save'}, 'Connection refused');
        cb(403);
    }
};

Is there a more elegant way to validate parameters received from client similar to the above syntax from PHP but in node.js. I reverted to basic "if &&" in order to check 2 simple parameter, but as you can see, it is extensive.


texts: Filling up a numpy array using data from a list

texts:
I am looking to optimize the nested for-loops shown in the code below.

I have a list, mixtures, that contains points that represent 1 Gaussian Mixture (GM) on each line. My goal is to run a function kl_divergence between all combinations of GM's (with i≠j) and store the results in an array PxP.

Note: The following mixtures list  is a simplified version of the actual list. In my original code, I am working with a lot more data.

import numpy as np
from sklearn.mixture import GaussianMixture

def kl_divergence(gmm_i, gmm_j, n_samples=10**5):
    X = gmm_i.sample(n_samples)
    log_p_i = gmm_i.score_samples(X[0])
    log_p_j = gmm_j.score_samples(X[0])
    return log_p_i.mean() - log_p_j.mean()

mixtures = [[[1, 3, 4, 7], [3, 5, 9, 2], [4, 3, 6, 1], [4, 3, 6, 3]],
            [[3, 4, 8, 2], [3, 6, 3, 7], [2, 6, 8, 4]],
            [[4, 8, 9, 3], [2, 6, 5, 8], [2, 5, 3, 5]],
            [[4, 9, 0, 2], [2, 4, 8, 3], [9, 8, 2, 3], [2, 6, 8, 3]]]
#Note: Each line has a different number of points

P_comp = len(mixtures)
PxP = np.zeros((P_comp, P_comp), dtype=int)

for row_i, GM_i in enumerate(mixtures):    #Loop through mixtures using i
    gmm_i = GaussianMixture(n_components=1).fit(GM_i)
    for row_j, GM_j in enumerate(mixtures): #Loop through mixtures using j
        if GM_i is not GM_j: #Skip if same mixture
            gmm_j = GaussianMixture(n_components=1).fit(GM_j)
            PxP[row_i, row_j] = kl_divergence(gmm_i, gmm_j) #Store result at index (row_i, row_j)

print("PxP\n", PxP)


texts: Performance impact of using reflection instead of an "Options" class

texts:
I am trying to refactor a service by providing some options on what to bring back. I can't decide what is best way to go between the below
A. Use a class for the options
Create a new class for the options like
    public class Options
    {
        public bool Addresses { get; set; }
        public bool Documents { get; set; }
    }

and call the services as below
    public List<Entity> GetEntitiesByOptions(List<int> entityIds, Options options)
    {
        if (options.Addresses)
        {
            // Add the addresses
        }

        if (options.Documents)
        {
            // Add the Documents
        }
    }

or B. Use the type of class as a parameter
and use with something like that
    public List<Entity> GetEntitiesByOptions(List<int> entityIds, List<Type> options)
    {
        if (options.Any(x => x == typeof(Address)))
        {
            // Add the addresses
        }

        if (options.Any(x => x == typeof(Document)))
        {
            // Add the Documents
        }
    }

Would there be a big impact in the performance if I use reflection?


texts:
I am trying to account for the errors in double arithmetic in a C# program I am writing, and came up with this first solution that seems to work well for most cases:

    double errorMargins = returnDouble * Double.Parse(Unit_Class_Library.Properties.Resources.AcceptedDeviationConstant);
    double roundedValue = 0;
    for (int i = 1; i <= returnDoubleAsString.Length; i++)
    {
        roundedValue = RoundToSignificantDigits(returnDouble, i);
        if (Math.Abs(roundedValue - returnDouble) < Double.Parse(Unit_Class_Library.Properties.Resources.AcceptedDeviationConstant))
        {
            returnDouble = roundedValue;
            i = returnDoubleAsString.Length;
        }

    }

    return returnDouble;
}

public static double RoundToSignificantDigits(double d, int digits)
{
    if (d == 0)
        return 0;

    bool isNegative = false;
    if (d < 0)
        isNegative = true;

    double scale = Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(d))) + 1);
    double returnValue =  scale * Math.Round(d / scale, digits);

    if (isNegative)
        returnValue = -returnValue;

    return returnValue;
}

However, I found that when you convert a number to a string it rounds the number making the above function not work.

For example, when 720.72499999999991 is inputted (with a AcceptedDeviationConstant of 0.000000001), the double as string would be "720.725" which causes the above loop to exit prematurely and not do its job leaving the number as 720.72499999999991. So what I did was convert the double to a string and then back to a double (the code block below) and this seems to work how I wanted it too, returning 720.725 in the above example.

string returnDoubleAsString = "" + returnDouble;
returnDouble = double.Parse(returnDoubleAsString);

I was wondering if it is okay to just leave it as the second one but it seems "improper" to do it like this. If it is okay in practice, what kind of comment should I leave to make it clear to other programmers what is going on and is there a link I can put in the comment that explains why this works?


texts: Integral implemented using a trapezoidal Riemann sum

texts:
I tried to make this a general purpose integral function but I want to know if it's efficient and idiomatic Rust.

use std::mem;

/// calculates the signed area between the function f and the x axis from
/// x = a to b using a trapezoidal Riemann sum. precision is the number of
/// trapezoids to calculate
pub fn integral<F>(a: f64, b: f64, f: F, precision: u32) -> f64
    where F: Fn(f64) -> f64 {

    let mut a = a;
    let mut b = b;

    let mut sign = 1.0;

    if a > b {
        mem::swap(&mut a, &mut b);
        sign = -1.0;
    }

    let delta = (b - a).abs() / precision as f64;
    let mut result = 0.0;

    for trapezoid in 0..precision {
        let left_side = a + (delta * trapezoid as f64);
        let right_size = left_side + delta;

        result += 0.5 * (f(left_side) + f(right_size)) * delta;
    }

    result * sign
}

And here's a test case

fn f(x: f64) -> f64 {
    (3.0 * x * x) + (4.0 * x) + 7.0
}

fn main() {
    let a = integral(0.0, 11.5, f, 1000000);
    println!("{}", a); // expect approx 1865.88
}


texts:
Is there a better way to write the JS for this? I'm asking because I read from somewhere that using .hover isn't recommended. Also, if I move the mouse in and out of the box really fast, the box fades in and out the exact number of times I entered/left the box. How do I prevent this?

jsFiddle

$(".project-mask").hover(
    function() {
        $(".thumbnail").fadeOut(300);
        $(".description").fadeIn(300);
    },
    function() {
        $(".thumbnail").fadeIn(300);
        $(".description").fadeOut(300);
    }
);
.project-mask { height:260px;position:relative;width:260px }
.thumbnail, .description { position:absolute;width:100% }

blah blah blah


texts:
A question I've been asked on interactive phone screens is to code a test to determine whether a string is
a palindrome or not. I am providing two examples here: one in C and one in C++. They both work and they both compile
without errors or warnings. I believe my C example is good, with the possible exception of variable names
(some of you may not like the register char* declarations, but they are valid in C).

My goal was an \$O(n)\$ solution with out reversing the string.

My question is about the C++ version, and I miss using iterators. Is there a way to make this more C++ like?

I can think in C; I can't necessarily think in C++.

Palindrome checker in C

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool palindromeChecker(char *possiblePalindrome)
{
    bool isPalindrome = true;
    size_t length = strlen(possiblePalindrome);

    if (length < 3)
    {
        isPalindrome = false;
    }
    else
    {
        register char *leftSide = possiblePalindrome;
        register char *rightSide = &possiblePalindrome[length-1];

        while ((leftSide < rightSide) && isPalindrome)
        {
            if (*leftSide != *rightSide)
            {
                isPalindrome = false;
            }
            leftSide++;
            --rightSide;
        }
    }

    return isPalindrome;
}

int main(int argc, const char * argv[]) {
    char testString[BUFSIZ];
    bool iSPalendrome;

    printf("Enter a test string to be checked for if it is a palindrome\n");
    scanf("%s", testString);
    iSPalendrome = palindromeChecker(testString);
    printf("The test string %s is %s a palindrome\n", testString, (iSPalendrome? "" : "Not"));

}

Palindrome checker in C++

#include <iostream>
#include <string>

bool IsPalindrome(std::string PossiblePalindrome)
{
    bool Palidrime = true;

    if (PossiblePalindrome.size() < 3)
    {
        Palidrime = false;
    }
    else
    {
        std::string::iterator leftSide = PossiblePalindrome.begin();
        std::string::iterator rightSide = PossiblePalindrome.end();
        rightSide--; // end is past the end of the possible palindrome so decrement to point to a character.

        while ((leftSide < rightSide) && Palidrime)
        {
            if (*leftSide != *rightSide)
            {
                Palidrime = false;
            }
            leftSide++;
            rightSide--;
        }
    }

    return Palidrime;
}

int main(int argc, const char * argv[]) {
    // insert code here...
    std::string PossiblePalindrome;
    std::cout << "Enter a string to test to see if it is a palindrome.\n";
    std::cin >> PossiblePalindrome;

    std::cout << "The string " << PossiblePalindrome;
    if (IsPalindrome(PossiblePalindrome))
    {
        std::cout << " is";
    }
    else
    {
        std::cout << " is not";
    }
    std::cout << " a palindrome" << std::endl;
}


texts: CSV to Object converter with JavaDoc comments

texts:
This is a simple class but I'm looking to check I have the basics down to scratch.

Is my documentation thorough enough? (I'm very new to writing JavaDoc) Have I created too many variables, and does this sacrifice performance for readability in a bad way?

This class is called once to create an array of TestDataObjects to use with our Parsing unit tests.

    /**
 * Converts our test data csv in to an ArrayList
 * We divide the csv entries up line by line for each calendar event then create a TestData object from each line.
 * The fields we wish to parse have negated new line characters to ensure they don't interfere with the csv parsing.
 * Once the csv has been parsed we need to unnegate these so the test data is the same as the original data.
 * @param calendar The csv to convert
 * @return An Array List of TestData objects that have all the three fields we wish to parse and the correct results we wish to obtain.
 */
private ArrayList<TestData> loadTestData(String calendar) {
    ArrayList<TestData> testDataArray = new ArrayList<>();
    String[] lines = calendar.split("\r\n");

    // always skip lines[0] as it contains the headers
    for (int i = 1; i < lines.length; ++i) {
        ArrayList<String> fields = CSVReader.parseLine(lines[i]);
        String title = fields.get(0).replace("\\n", "\n");
        String location = fields.get(1).replace("\\n", "\n");
        String description = fields.get(2).replace("\\n", "\n");
        ArrayList<String> correctHostCodes = CSVReader.parseLine(fields.get(3));
        ArrayList<String> correctParticipantCodes = CSVReader.parseLine(fields.get(4));
        ArrayList<String> correctPhoneNumbers = CSVReader.parseLine(fields.get(5));

        TestData testDataObject = new TestData(title + "\n" + location + "\n" + description, correctHostCodes, correctParticipantCodes, correctPhoneNumbers);
        testDataArray.add(testDataObject);
    }

    return testDataArray;
}


texts:
I am trying to implements a map (that can work as a cache) that has strings as keys and values of different types. In my real case once set the key/values in the map will not change.

I used these classes, I take as example the Item 29 on Effective Java 2nd edition.

This is the class for values:

final class CachedValue {

    private Object value;

    public <T> void setValue(Class<T> type, T instance){

        if(type == null){

            log.error("type is null");

            throw new NullPointerException("Type is null");
        }

        value = type.cast(instance);
    }

    public <T> T getValue(Class<T> type){

        return type.cast(value);
    }
}

This for the map that works like a cache:

  public final class Cache {

            private final Map<String, CachedValue> map = Maps.newHashMap();

            public <T> void put(String key, Class<T> type, T value){

                CachedValue cachedValue = new CachedValue();

                cachedValue.setValue(type, value);

                map.put(key, cachedValue);
            }

            public <T> T get(String key, Class<T> type){

                return map.get(key).getValue(type);
            }

            public boolean contains(String key){

                return map.containsKey(key);
            }

      }

Can someone review my code and tell me if it's right or if it can be simplify? I don't need it to be thread-safe.


texts:
I have the following code:

 Visitors

            <?php while($visitor = $visitors->fetch_object()) { ?>
            <?php $time = $visitor->time; ?>
            <?php $visitor = new User($visitor->viewer_id); ?>
            <?php
            $this->insert('visitors/visitor',[
            'id' => $visitor->id,
            'profile_image' => $visitor->profile_image,
            'name' => $visitor->name,
            'time' => $time->convertToAgo($time);
            ]);
            ?>
            <? } ?>

I've been trying to think of a way to better separate the logic from the presentation. I'm already using a template engine (Plates, native php templating), this code is from one of my template files. However, as it stands, it won't easy for anyone who has no understanding of PHP to edit my template file without getting confused with all of the PHP code.

Can anyone help me with ideas on the way to do this logic/presentation separation?


texts:
This question is about the best way to declare functions in Javascript. The app is a small 2 player board game I'm working on as part of a bigger web page. Basically I have a socket which receives and send messages and the game acts according to the content of the message.

$(function () {
    var board = document.getElementById('board');
    //When a msg is received
    //structure of msg : msg = ['action','args']
    if (msg[0] === 'action1') {
        func1(args);
    } else if (msg[0] === 'action2') {
        func2(args);
    }
}

function func1(args) {
    var a, b...;
    doAction1(); //uses the DOM element board, the args and local variables
}

function func2(args) {
    var a, b...;
    doAction2();
}

Now, I was thinking of using an object the way I would do in Java but it seems that it is not the best practice. Should I use a single function like so?

$(function () {

    var game = function () {
        var gamevar1, gamevar2, ...;
        action1: function (arg) {
            doAction1();
        }

        action2: function (arg) {
            doAction2();
        }
    }

    //when a msg is received [action,param]
    game.msg[0](msg[1]);
}


texts:
I decided to make a password generator to get more familiar with Python.
I had to break up the code into two boxes due to weird Stack Exchange highlighting with the triple quotes.
How would you improve this program on the grounds of:

Readability/cleanness,
Performance, and
Security.

Feel free to include any other comments you have on it that may not fit into those three categories.
import string
import random
import secrets
import argparse
import MyFormatter

alphaL = list(string.ascii_lowercase)
alphaU = list(string.ascii_uppercase)
numeric = list(string.digits)
special = list("!@#$%^&*")
special2 = list("""~`!@#$%^&*()+=_-{}[]\|:;"'?/<>,.""")

parser = argparse.ArgumentParser(
    formatter_class=MyFormatter.MyFormatter,
    description="Generates a password",
    usage="",
)

parser.add_argument("-lc", "--lower", type=int, default=1, help="Minimum number of lowercase alpha characters")
parser.add_argument("-uc", "--upper", type=int, default=1, help="Minimum number of uppercase alpha characters")
parser.add_argument("-n", "--numeric", type=int, default=1, help="Minimum number of numeric characters")
parser.add_argument("-s", "--special", type=int, default=1, help="Minimum number of special characters")
parser.add_argument("-se", "--extended", action = 'store_const', default = False, const= True, help="Toggles the extendard special character subset. Passwords may not be accepted by all services")
parser.add_argument("-l", "--length", type=int, default=20, help="Length of the generated password")

args = parser.parse_args()

length = args.length

minimums = [
    args.lower,
    args.upper,
    args.numeric,
    args.special,
]

password = ""

for i in range(0, minimums[0]) :
    password += secrets.choice(alphaL)

for i in range(0, minimums[1]) :
    password += secrets.choice(alphaU)

for i in range(0, minimums[2]) :
    password += secrets.choice(numeric)

if args.extended :
    subset = alphaL + alphaU + numeric + special2
    for i in range(0, minimums[3]) :
        password += secrets.choice(special2)
elif minimums[3] :
    subset = alphaL + alphaU + numeric + special
    for i in range(0, minimums[3]) :
        password += secrets.choice(special)

for i in range(0, 100) :
    random.shuffle(subset)

for i in range(len(password), length) :
    password += secrets.choice(subset)

for i in range(0, 100) :
    password = ''.join(random.sample(password, len(password)))

print("Password: ", password)


texts:
I have this PHP code. I wrote it for a webpage it uses parameters. Only one set of parameters can be set at any one time. If both are set its invalid, if None are set its invalid

How would be the best way to write it, looks too long to me and i Feel like I have complicated it

if($_REQUEST['b_id'] && $_REQUEST['s_id']) {
        die('Not A Valid Request URL');
}
if(!$_REQUEST['b_id']) {
        $b = false;
} else {
        $b = true;
}

if(!$_REQUEST['s_id']){
           $s = false;
} else {
           $s = true;
}

if($b === $s) {
        die('Not A Valid Request URL');
} else if($_REQUEST['b_id'] == $_REQUEST['s_id']) {
      die('Not A Valid Request URL');
}

PS the code works as expected. I just need help making it neater little less confusing.


texts:
I wrote a simple javascript program that takes a user's input and calculates the cost of their commute. I feel like I'm repeating a lot of stuff though.

How could I refactor this to make it cleaner and more concise?

function calcCost(costOfGas, vehicleMPG, numMiles) {
  var dailyCost = (costOfGas / vehicleMPG) * (numMiles * 2);
  var weeklyCost = dailyCost * 5;
  var monthlyCost = weeklyCost * 4;

  return {
    dailyCost: dailyCost,
    weeklyCost: weeklyCost,
    monthlyCost: monthlyCost
  };
}

var form = document.forms[0];

form.onsubmit = function(e) {
  e.preventDefault();

  if (form.costOfGas.value == '' ||
    form.vehicleMPG.value == '' ||
    form.numMiles.value == '')
  {
    return;
  }
  else
  {
    var userCostOfGas = +form.costOfGas.value;
    var userMPG = +form.vehicleMPG.value;
    var userNumMiles = +form.numMiles.value;

    form.costOfGas.value = '';
    form.vehicleMPG.value = '';
    form.numMiles.value = '';

    var costs = calcCost(userCostOfGas, userMPG, userNumMiles);

    var inputReturned = document.getElementById("inputReturned");
    inputReturned.innerHTML = "For a car that gets " + userMPG +
    " MPG, driving " + userNumMiles + " miles to work each day at $" +
    userCostOfGas.toFixed(2) + "/gal:";

    calculatedDailyCost.innerHTML = "You're spending $" + costs.dailyCost.toFixed(2) + " on gas every day.";
    calculatedWeeklyCost.innerHTML = "You're spending $" + costs.weeklyCost.toFixed(2) + " on gas every week.";
    calculatedMonthlyCost.innerHTML = "You're spending $" + costs.monthlyCost.toFixed(2) + " on gas each month.";
  }
};


texts: Polymorphic customer classes for employees and affiliates

texts:
I was trying to achieve a simple problem :

If the user is an employee of the store, he gets a 30% discount
If the user is an affiliate of the store, he gets a 10% discount

I came up with the following :

The abstract super class :

abstract class Customer {
String cid;
String customer_name;
double fare;

Customer(){
    this.cid="NA";
    this.customer_name="NA";
    this.fare=0.0d;
}
protected String getCid() {
    return cid;
}

protected String getCustomer_name() {
    return customer_name;
}

protected abstract double getFare();
protected abstract void printDetails();
}

The child class :

class CustomerAffiliated extends Customer{

    CustomerAffiliated(String cid,String customer_name,double fare){

        super();
        this.cid=cid;
        this.customer_name=customer_name;
        this.fare=fare;
    }

    @Override
    protected double getFare() {

        return this.fare-((10.0/100.0) * this.fare);
    }

    @Override
    protected void printDetails() {
        System.out.println(this.getCid());
        System.out.println(this.getCustomer_name());
        System.out.println(this.getFare());
    }
}

And like wise the other child class.
Calling the methods something like :

Customer c;
    c=new CustomerAffiliated("1","a",100);
    c.printDetails();

Am I doing it in a right way? I did not preferred composition as it is (is a) relation. Moreover I am able to use all the fields in the parent class.
Is is the correct approach ?


texts: Adding credentialsID node to SVN location nodes

texts:
I'm new to ruby. Recently I wrote a script to add a credentialsID node to each SVN location node in each config.xml file for all of our Jenkins jobs (We have many).

It works, but I'm guessing it could be done more elegantly. How would you fix this to be more succinct, clean, etc.

require 'nokogiri'

Dir["somepathhere/.jenkins/jobs/*/config.xml"].each do |filename|

    file = File.open(filename, 'r')
    doc = Nokogiri::XML(file)
    file.close
    locations = doc.xpath('/project/scm/locations/hudson.scm.SubversionSCM_-ModuleLocation')
    locations.each do |location|
        crednode = location.at_xpath('credentialsId')
        if crednode
            crednode.content = 'somevalue'
        else
            location.first_element_child.before("<credentialsId>somevalue</credentialsId>\n")
        end
    end
    File.open(filename, 'w') { |file| file.print(doc.to_xml) }
end


texts: Simplified encryption API wrapper for RSA and AES

texts:
I'm working on an encryption library to simplify how my team uses encryption for api credentials and receiving encrypted messages from other teams/projects.

This code is wrapping java.security and BouncyCastle implementations. These classes are just simplifying the calls to those libraries. But I'm struggling with designing the appropriate abstraction for my top-level classes.

I started with these top-level interfaces to define the domain:

public interface Key {
    byte[] getBytes();
}

public interface Message {
    byte[] getBytes();
}

public interface Secret {
    byte[] getBytes();
}

public interface Decrypter {
    Message decrypt(Secret secret, Key key);
}

public interface Encrypter {
    Secret encrypt(Message message, Key key);
}

This worked well to wrap RSA encryption:

public class KeyPair {
    private final Key publicKey;
    private final Key privateKey;

    public Key getPublicKey() {
        return publicKey;
    }

    public Key getPrivateKey() {
        return privateKey;
    }
}

public class RsaEncrypter implements Encrypter {

    @Override
    public Secret encrypt(Message message, Key publicKey) {
        // Perform Encryption
    }
}

public class RsaDecrypter implements Decrypter {
    @Override
    public Message decrypt(Secret secret, Key privateKey) {
        // Perform the decryption
    }
}

But now that I'm applying it to our AES Encryption use cases I've encountered a problem. The Secret contains an InitializationVector because we're using AES in CBC mode.

So I've got this:

public class AesSecret implements Secret {
    private byte[] cipherText;
    private byte[] initilizationVector;

    @Override
    public byte[] getBytes() {
        return cipherText;
    }

    public byte[] getInitilizationVector() {
        return initilizationVector;
    }
}

public class AesDecrypter implements Decrypter {
    @Override
    public Message decrypt(Secret secret, Key key) {
        try {
            return decrypt((AesSecret) secret, key);
        } catch (ClassCastException e) {
            throw new IllegalArgumentException("AesDecrypter only supports subclasses of AesSecret", e);
        }
    }

    public Message decrypt(AesSecret secret, Key key) {
        // Do the AES Decryption
    }
}

The ClassCastException makes me think that I'm violating the Liskov Substitution Principle, and introducing the parallel hierarchy code-smell. I've read the Visitor pattern is a common solution to this code smell, but I haven't figured out how it would apply to my situation.

Any suggestions? Or am I over-thinking this?


texts: An attempt at inheritance (Geometric Shapes)

texts:
I'm reading through the chapter on inheritance from C++ Primer 5th Edition. It asks

Organize the following type into an inheritance hierarchy:
(b) Geometric primitives (such as box, circle, sphere, cone)
Identify some of the likely virtual functions as well as public and protected
members.

I was hoping this is a suitable arrangement for the organisation of the hierarchy. My line of thinking was:

The most general property of any shape is its dimension. Thus the code could be factored in to having a base class at the top named Shape which would contain this piece of data.

The necessary member functions will change depending on whether I have a 1D, 2D or 3D shape. 2D shapes will require an area and perimeter function, and 3D shapes a surfaceArea and volume function. The operations of these functions will vary depending on the shape. So define abstract base classes corresponding to each dimension with pure-virtual member functions.

Derive classes from the dimension classes corresponding to the final geometric shapes.

My main concern is that maybe the Shape class isn't all that necessary if its only purpose is to hold dimension and the static member pi. A second concern is how to prevent creation of Shape objects, since it only represents a concept and nothing tangible. I'm guessing to do this I would need to define the destructor as pure virtual - although I have not reached this stage of reading.
Shape.h:
#ifndef SHAPE
#define SHAPE

#include <cmath> //sqrt needed

class Shape{
public:
    Shape() = default;
    Shape(unsigned d): dimensions(d) { }
    virtual ~Shape() = default;
private:
    unsigned dimensions = 0;
protected:
    static const double pi;

};

class DimensionOne : public Shape {
public:
    DimensionOne(): Shape(1) { }

    virtual double length() const = 0;
};

class DimensionTwo : public Shape {
public:
    DimensionTwo(): Shape(2) { }

    virtual double perimeter() const = 0;
    virtual double area() const = 0;
};

class DimensionThree : public Shape {
public:
    DimensionThree(): Shape(3) { }

    virtual double surfaceArea() const = 0;
    virtual double volume() const = 0;
};

//2D SHAPES

class Rectangle : public DimensionTwo {
public:
    Rectangle() = default;
    Rectangle(double a): DimensionTwo(), length(a), width(a) { }
    Rectangle(double x, double y): DimensionTwo(), length(x), width(y) { }

    double perimeter() const override { return 2*(length+width); }
    double area() const override { return length*width;}
private:
    double length = 0, width = 0;
};

class Circle : public DimensionTwo {
public:
    Circle() = default;
    Circle(double r): DimensionTwo(), radius(r) { }

    double perimeter() const override { return 2*pi*radius; }
    double area() const override { return pi*radius*radius;}
private:
    double radius = 0;
};

//3D SHAPES

class Box : public DimensionThree {
public:
    Box() = default;
    Box(double a): DimensionThree(), length(a), width(a), height(a) { }
    Box(double x, double y, double z): DimensionThree(), length(x), width(y), height(z) { }

    double surfaceArea() const override { return (2*length*height) + (4*width*height); }
    double volume() const override { return length*width*height;}
private:
    double length = 0, width = 0, height = 0;
};

class Sphere : public DimensionThree {
public:
    Sphere() = default;
    Sphere(double r): DimensionThree(), radius(r) { }

    double surfaceArea() const override { return (4*pi*radius*radius); }
    double volume() const override { return (4*pi*radius*radius*radius)/3;}
private:
    double radius = 0;
};

class Cone: public DimensionThree {
public:
    Cone() = default;
    Cone(double b, double h): DimensionThree(), base(b), height(h) { }

    double surfaceArea() const override { return pi*base*(base + sqrt(base*base + height*height)); }
    double volume() const override { return (pi*base*base*height)/3;}
private:
    double base = 0, height = 0;
};

#endif // SHAPE

Shape.cpp:
#include "Shape.h"

const double Shape::pi = 3.14159;


texts:
I recently put in a submission for a small coding challenge using Angular. The challenge was to get a token and array of values using a GET request then make another GET request passing the token and sum of values within the url. I'm still getting to grips with promises and want to know if the flow in the service and controller code below can be improved. For me the problematic line is returning the helper function solveChallenge from within the getChallenge function. It works but is my use of promises good or an anti-pattern? Should I be using the success and error methods provided by $http in place of then and catch? Any other feedback on the code is definitely much appreciated.

dataservice.js

(function() {
    'use strict';

    angular
      .module('app')
      .factory('dataservice', dataservice);

    dataservice.$inject = ['$http', '$log'];

    function dataservice($http, $log) {
        var sum, token, challenge;

        return  {
            getChallenge: getChallenge
        };

        function getChallenge(url) {

            return $http.get(url)
                    .then(function(data, status, headers, config) {
                        token = data.data.token;
                        sum = sumArray(data.data.values);
                        challenge = {token, sum};
                        return solveChallenge(url, challenge);
                    })
                    .catch(function(data, status, headers, config) {
                        $log.error("The request failed. Error code: " + status);
                    });
        }

        function solveChallenge(url, challenge) {
            var sum, token, solutionUrl;

            sum = challenge.sum;
            token = challenge.token;
            solutionUrl = url + '/' + token + '/' + sum;

            return $http.get(solutionUrl)
                    .then(function(data, status, headers, config) {
                        return data.data.answer;
                    })
                    .catch(function(data, status, headers, config) {
                        $log.error("The request failed. Error code: " + status);
                    });

          }
    }

    function sumArray(items) {
        var sum = 0;
        for (var i = 0; i < items.length; i++) {
            sum += items[i];
        }
        return sum;
    }

})();

controller.js

(function() {
    'use strict';

    angular.module('app').controller('Controller', Controller);

    Controller.$inject = ['dataservice'];

    function Controller(dataservice) {
        var vm = this;

        vm.showMeTheChallenge = function() {

          dataservice.getChallenge('http://the-url/challenge')
            .then(function(response) {

              vm.challengeSolution = response;

          });

        };
        vm.resetChallenge = function() {

            vm.challengeSolution = null;

        }

    }

})();


texts: Rotating background using Swing: performance issues

texts:
In a jPanel, I'm displaying a 1203x1203 background that I rotate every 30ms. Problem is, Swing is known to be a slow library, and I assume rotating a huge picture at a quick rate would be quite resources demanding. But I've a powerful PC, and even if on mine it runs fine, I wonder if on slower machines it will be as fluid.

public static BufferedImage createRotatedCopy(BufferedImage img, double rotation) {
    int w = img.getWidth();
    int h = img.getHeight();
    BufferedImage rot = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    double theta = 2 * Math.PI * rotation;
    AffineTransform xform = new AffineTransform();

    xform.translate(0.5 * h, 0.5 * w);
    xform.rotate(theta);
    xform.translate(-0.5 * w, -0.5 * h);
    Graphics2D g = (Graphics2D) rot.createGraphics();
    g.drawImage(img, xform, null);
    g.dispose();
    return rot;
}

I wonder first if there is any way to optimize it. What I can do, is to use a smaller picture, apply the rotation and resize it. But I don't know if it would be more efficient.

And the rotation callback is:

    exec = Executors.newSingleThreadScheduledExecutor();
    exec.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            bgAngle += 0.001;
            bgAngle = (bgAngle >= 1) ? 0 : bgAngle;
            rotBg = Menu.createRotatedCopy(toBufferedImage(bg.getImage()),
                    bgAngle);
            repaint();
        }
    }, 0, 30, TimeUnit.MILLISECONDS);

Do you see anything that could be optimized? Or outright another way to do what I want?


texts:
I'm seeing a web course of computational statistics, the first project consists of a random walker, the implementation I have done works as intended:
import numpy as np
import numpy.random as rd
import matplotlib.pyplot as plt

WALKER_STEPS: int = 5_000

# random orientation converted from degrees to radians
directions: np.array = rd.uniform(low=0, high=360, size=WALKER_STEPS) * np.pi / 180

x: list = [0]
y: list = [0]
idx: int = 0
for rad in directions:
    # updates the positions of the walker
    x.append(x[idx] + np.cos(rad))
    y.append(y[idx] + np.sin(rad))
    idx += 1

plt.plot(x, y)
plt.show()

I don't like the way I'm adding new elements to the lists x, y and I think that there's a more elegant way to do it.
Here a image of the result:

Note: I didn't do an abstraction because the exercise in small.


texts:
I'm trying to find the fastest way to enqueue and dequeue items concurrently in Go.

There are some restrictions:

it needs to be unbounded
Memory allocation should be low
Multiple producers
(Single consumer)

This is what I've come up with so far:

package queue

import "sync"

type Queue struct {
    buffer []interface{}
    head   int           //index where items are poped
    tail   int           //index where items are pushed
    len    int           //current len of queue
    mod    int           //ring size
    lock   sync.RWMutex
}

func New() *Queue {
    initialSize := 10
    return &Queue{
        buffer: make([]interface{}, initialSize),
        head:   0,
        tail:   0,
        len:    0,
        mod:    initialSize,
    }
}

func (q *Queue) Push(item interface{}) {
    q.lock.Lock()
    defer q.lock.Unlock()
    q.tail = ((q.tail + 1) % q.mod)
    if q.tail == q.head { //if head equals tail, the ring is too small, resize
        fillFactor := 2   //how much should the buffer grow

        newLen := q.mod * fillFactor
        newBuff := make([]interface{}, newLen)

        //unwind the current buffer on the new larger buffer
        for i := 0; i < q.mod; i++ {
            buffIndex := (q.head + i) % q.mod
            newBuff[i] = q.buffer[buffIndex]
        }
        //set the new buffer and reset head and tail
        q.buffer = newBuff
        q.head = 0
        q.tail = q.mod
        q.mod *= fillFactor
    }
    q.len++
    q.buffer[q.tail] = item //place the item on the buffer
}

..//Length and Empty method removed

func (q *Queue) Pop() (interface{}, bool) {
    q.lock.Lock()
    defer q.lock.Unlock()

    if q.len == 0 {  //early exit if no items

        return nil, false
    }
    //move head to next ring index, consume it and reduce length
    q.head = ((q.head + 1) % q.mod)
    q.len--
    return q.buffer[q.head], true
}

func (q *Queue) PopMany(count int) ([]interface{}, bool) {
    q.lock.Lock()
    defer q.lock.Unlock()
    if q.len == 0 {
        return nil, false
    }

    if count >= q.len {
        count = q.len
    }

    buffer := make([]interface{}, count)
    for i := 0; i < count; i++ {
        buffer[i] = q.buffer[(q.head+1+i)%q.mod]
    }
    q.head = (q.head + count) % q.mod
    q.len -= count
    return buffer, true
}

This implementation works, and is currently the one that gives me the best sustained throughput. Known issues with this one is that it never down size the buffer when the length is shrinking.

I've tried the queue implemented in Go Data Structures, but it simply eats too much memory when under high load.

There is also a lock free ring buffer in the same package, but that one is bounded.

I figured as there is only a single consumer, it might be possible to make the Pop() lock free (?). as long as there are at least 1 item in the queue, it should be possible to pop it w/o locking, I think. The problem is when the producers cause a resize event to occur, then the Pop needs handle that somehow.

Any feedback is welcome, coding conventions, optimiation tricks etc. I'm fairly new to Go so there might be issues.


texts: Embarking on a Tic Tac Toe journey with JavaFX

texts:
On my educational trek through the capabilities of JavaFX, I thought it would be a valuable challenge to create Tic Tac Toe. It took me far longer than expected to get this far, but despite likely being even further from completion, I'd like a review on the current state of things and on anything my 'blind coding' unwittingly implemented unconventionally/inefficiently/just plain weirdly.

Some names may seem strange, but that could be due to my editing the image-related code to point to URLs rather than local files for the sake of this post.

TicTacToe main class:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class TicTacToe extends Application {
    static Player player = Player.O_PLAYER;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        Button[] cells = new Button[9];
        for (int i = 0; i < cells.length; i++) {
            cells[i] = new Button("",
            new ImageView(new Image("http://i.imgur.com/KAQPbPd.png")));
            registerOnAction(cells[i]);
        }

        GridPane board = new GridPane();
        for (int row = 1, col = 1, cell = 0; row <= 3; row++, col -=2) {
            board.add(cells[cell++], row, col++);
            board.add(cells[cell++], row, col++);
            board.add(cells[cell++], row, col);
        }

        Scene scene = new Scene(board);
        stage.setScene(scene);
        stage.setTitle("TicTacToe By Legato");
        stage.getIcons().add(new Image("http://i.imgur.com/gxhJkc0.png"));
        stage.show();
    }

    private static Image retrieveMarker() {
        player = player == Player.X_PLAYER ? Player.O_PLAYER : Player.X_PLAYER;
        return player.marker();
    }

    private static void registerOnAction(Button button) {
        button.setOnAction(e ->
            button.setGraphic(new ImageView(retrieveMarker()))
        );
    }
}

Player enum:

import javafx.scene.image.Image;
import javafx.scene.image.ImageView;

public enum Player {
    X_PLAYER(new ImageView(new Image("http://i.imgur.com/HY6GeUY.png"))),
    O_PLAYER(new ImageView(new Image("http://i.imgur.com/KgHHxL6.png")));

    private final ImageView view;

    Player(ImageView view) {
        this.view = view;
    }

    public Image marker() {
        return view.getImage();
    }

    @Override
    public String toString() {
        return name().charAt(0) + name().substring(2).toLowerCase();
    }
}

Follow-ups:

Completed Tic-Tac-Toe.
Tic-Tactics.


texts: Is it possible to make a generic method out of this, or at least separate them?

texts:
I'm using ImageProcessor in C# and I can't come up with a way to make a generic method out of its methods as to avoid writing the same code more than once.

Say, I have two methods, crop and resize.

 public Image Resize(Image image, int width, int height)
{
    // Create a Image to be returned after being scaled, call it resizedImage:
    Image resizedImage;
    // Create a Size for the image to be scaled to, call it size:
    var size = new Size(width, height);
    // Create an ImageFactory to process the image, call it imageFactory:
    using (var imageFactory = new ImageFactory(preserveExifData: true))
    {
        // Create a MemoryStream to temporarily store the processed image, call it imageStream:
        using (var imageStream = new MemoryStream())
        {
            // Scale the image using the ImageProcessor library
            // Load the image to be resized, resize it and save it to the MemoryStream:
            imageFactory.Load(image)
                        .Resize(size)
                        .Save(imageStream);
            // Assign the processed image to the previously declared resizedImage:
            resizedImage = Image.FromStream(imageStream);
        }
    }

    // Return the resized image:
    return resizedImage;
}
public Image Crop(Image image, float left, float top, float right, float bottom, bool isModePercentage = true)
{
    // Create a Image to be returned after being cropped, call it croppedImage:
    Image croppedImage;
    // Create a CropMode to specify what cropping method to use (Percentage or Pixels), call it cropMode
    // If isModePercentage = true we use CropMode.Percentage, otherwise use CropMode.Pixels:
    var cropMode = isModePercentage ? CropMode.Percentage : CropMode.Pixels;
    // Create a CropLayer to specify how and how much the image should be cropped, call it cropLayer:
    var cropLayer = new CropLayer(left, top, right, bottom, cropMode);
    // Create an ImageFactory to process the image, call it imageFactory:
    using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
    {
        // Create a MemoryStream to temporarily store the processed image, call it imageStream:
        using (MemoryStream imageStream = new MemoryStream())
        {
            // Crop the image using the ImageProcessor library
            // Load the image to be cropped, crop it and save it to the MemoryStream:
            imageFactory.Load(image)
                        .Crop(cropLayer)
                        .Save(imageStream);
            // Assign the processed image to the previously declared croppedImage:
            croppedImage = Image.FromStream(imageStream);
        }
    }
    // Return the cropped image:
    return croppedImage;
}

How can I avoid having to instantiate imagefactory and memory stream multiple times, reducing the size of my methods and avoid to write the same code twice?


texts:
I am writing a function that, given a list and a target sum, returns zero-based indices of any two distinct elements whose sum is equal to the target sum. If there are no such elements, the function should return null.

For example,

 FindTwoSum(new List<int>() { 1, 3, 5, 7, 9 }, 12)

should return any of the following tuples of indices:

1, 4 (3 + 9 = 12)
2, 3 (5 + 7 = 12)
3, 2 (7 + 5 = 12)
4, 1 (9 + 3 = 12)

Note: I made my code return the first sum equal to 12.

So far, I came up with the following:

using System;
using System.Collections.Generic;

class TwoSum
{
    public static Tuple<int, int> FindTwoSum(IList<int> list, int sum)
    {
       int first_i =0, global_sum=0, second_i=1;

        if(list.Count == 0 || sum == 0 ){
            return null;
        }

        for(int i = first_i ; i< list.Count; i++)
        {
            for(int j=second_i; j<list.Count; j++)
            {
                        if(i != list.Count)
                            {
                                global_sum += list[i] + list[j];

                                if(global_sum == sum)
                                    {
                                         var tuple1 = Tuple.Create(i,j);
                                      return tuple1;
                                    }
                                global_sum = 0;
                            }
                        else
                            {
                                break;
                            }

            }
        }
        return null;

    }

    public static void Main(string[] args)
    {
        Tuple<int, int> indices = FindTwoSum(new List<int>() { 1, 3, 5, 7, 9 }, 12);
        Console.WriteLine(indices.Item1 + " " + indices.Item2);
    }
}

Everything was working fine and I scored 75%. But in terms of performance, my code did badly as I got a review saying:

  performance test- The code too long to calculate an answer. Analyse how your code behaves when the input increases in size and see if you can make it work faster


texts: increase efficiency of loops and element-wise operations in PyTorch implementation

texts:
For any input symmetric matrix with zero diagonals W, I have the following implementation in PyTorch. I was wondering if the following can be improved in terms of efficiency,
P.S. Would current implementation break backpropagation?
import torch

W = torch.tensor([[0,1,0,0,0,0,0,0,0],
                  [1,0,1,0,0,1,0,0,0],
                  [0,1,0,3,0,0,0,0,0],
                  [0,0,3,0,1,0,0,0,0],
                  [0,0,0,1,0,1,1,0,0],
                  [0,1,0,0,1,0,0,0,0],
                  [0,0,0,0,1,0,0,1,0],
                  [0,0,0,0,0,0,1,0,1],
                  [0,0,0,0,0,0,0,1,0]])

n = len(W)
C = torch.empty(n, n)
I = torch.eye(n)
for i in range(n):
    for j in range(n):
        B = W.clone()
        B[i, j] = 0
        B[j, i] = 0

        tmp = torch.inverse(n * I - B)

        C[i, j] = tmp[i, j]


texts:
I am building a Tic Tac Toe game with AngularJS and making it online playable with AngularFire.  The Tic Tac Toe logic is all there so this question concerns Angularfire a little bit more. I want to be able to match a user with an opponent as well as delete inactive games.

I have done my homework and at this point I want to get the smell out of my code.  Since I am handling asynchronous requests, I built a factory that returns a promise.

app.factory("GameCreator", ["$q","$firebase",function($q, $firebase){
    var deferred = $q.defer();
    var ref = new Firebase("https://myfirebase.firebaseio.com/");
    $firebase(ref).$on("loaded",function(value){
        var games = $firebase(ref);
        var IDs = games.$getIndex();
        var initGame = function(n){
            games.$add({
                //the board's state and turns, shared by all users
                board:[['','',''],['','',''],['','','']],
                xTurn:true,
                turns:0,
                playerone:{piece:'x', ready:false,won:false},
                playertwo:{piece:'o',ready:false,won:false},
                //helpers to sync and assign player
                xIsAvailable:false,
                oIsAvailable:true
            });
            //my opponent did something.  His/her actions need to appear on my screen.
            games.$on("change",function(){
                deferred.resolve( games.$child(games.$getIndex()[n]) );
            });
        };
        var n = IDs.length;
        //if no games, then build a game
        if(n == 0){
            initGame(n);
        }
        //else, determine placement in new vs existing game
        else{
            //if last - 1 has a spot, put me in that game, else create me a new game
            var checkThisGame = games.$child(IDs[n-1]);
            checkThisGame.$on('loaded',function(){
                if(checkThisGame.oIsAvailable == true){
                    checkThisGame.oIsAvailable = false;
                    checkThisGame.$save();
                    deferred.resolve(checkThisGame);
                }
                else{
                    initGame(n);
                }
            });
        }
    return deferred.promise;
    });
}])

In my controller, I then use the resolved promise to fulfill my objectives:

app.controller ('BoardCtrl', function($scope,$timeout,GameCreator,$window) {
    GameCreator.then(function(returnedData){
        returnedData.$on('loaded',function(){
            $scope.game = returnedData;
            var piece;
            if(returnedData.oIsAvailable == true) {
                piece = 'x';
            }
            else {
                piece = 'o';
            }
            $scope.myPiece = {
                val:piece
            };
            $window.onbeforeunload = function (event) {
                //delete this game from the firebase I/O
                returnedData.$remove();
                return null;
            }
            //the rest of the tic tac toe game logic follows here,
            //with all proper calls to $scope.game.$save()
        });
    });
);

Since I do not completely know what I am doing, I will ask: did I do this right?  Is there some refactoring that could be done?  It works as expected but I thought I would ask for a review.


texts: No more Fizzbuzz. How about Hello World instead?

texts:
Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”

It seems that we're shooting for one fizzbuzz question for each language. I'm sick of FizzBuzz, so I'm killing two birds with one stone. This code works in both vb6 and vba.

My goal here was to write a flexible Fizzbuzzer; one that could double as a Hello World program (of sorts). Is there anything left to say about it, or are we all FizzBuzzed out?

FizzBuzzer (Standard Module):

Option Explicit

Public Function Convert(ByVal number As Integer, Optional ByVal fizzDivisor As Integer = 3, Optional ByVal buzzDivisor As Integer = 5, Optional ByVal fizzWord As String = "Fizz", Optional ByVal buzzWord = "Buzz")

    If (number Mod fizzDivisor = 0) And (number Mod buzzDivisor = 0) Then
        Convert = fizzWord & buzzWord
    ElseIf (number Mod fizzDivisor = 0) Then
        Convert = fizzWord
    ElseIf (number Mod buzzDivisor = 0) Then
        Convert = buzzWord
    Else
        Convert = number
    End If

End Function

Example Calls:

Public Sub Main()

    Debug.Print "Standard Fizz Buzz"
    Dim i As Integer
    For i = 1 To 100
        Debug.Print (FizzBuzzer.Convert(i))
    Next i

    Debug.Print "Change the Numbers"
    For i = 1 To 100
        Debug.Print (FizzBuzzer.Convert(i, 4, 6))
    Next i

    Debug.Print "Change the Words"
    For i = 1 To 100
        Debug.Print (FizzBuzzer.Convert(i, fizzWord:="Hello", buzzWord:="World"))
    Next i

End Sub


texts: In Python, stylistically better way to remove a potentially nonexistent key from a dictionary?

texts:
Say you have a dictionary some_dict and want to make sure there's no key some_key in it. What's the best way to do this stylistically speaking and why?

Option 1

some_dict.pop(some_key, None)

Option 2

try:
    del some_dict[some_key]
except KeyError:
    pass

Option 3

if some_key in some_dict:
    del some_dict[some_key]

Also feel free to suggest another option.


texts:
I have written a little class that is intended to be used to spend unused time in a loop body, sleeping.

That is, I have a loop. I want every iteration to take at least X seconds. If the operations actually complete quicker, the excess time shall be spent sleeping.

My implementation is based on a class that is created in a scope, and whose destructor sleeps for the required amount of time when the object's lifetime ends.

Is this a sane approach to the problem? Are there any flaws in the implementation? Is there potential for improvements regarding coding style?

#include <chrono>
#include <thread>

class TimeSink {
public:
    typedef std::chrono::milliseconds duration_ms;

    TimeSink(duration_ms const & min_duration)
    : min_duration(min_duration), start(std::chrono::steady_clock::now()) {}

    ~TimeSink() {
        time_point end = std::chrono::steady_clock::now();
        auto elapsed = end-start;
        auto remaining_time_to_sleep = min_duration - elapsed;
        if (remaining_time_to_sleep > epsilon) {
            std::this_thread::sleep_for(remaining_time_to_sleep);
        }
    }

private:
    typedef std::chrono::time_point<std::chrono::steady_clock> time_point;
    const duration_ms epsilon = duration_ms(0);
    duration_ms min_duration;
    time_point start;
};

int main() {
    TimeSink t(TimeSink::duration_ms(1000));
}


texts:
I feel like there would be a better way to this. Essentially, I am transporting the data from an excel file to a DGV, and then from a DGV to an Access database. Should I cut the middle man or is this fine the way it is? The problem here is that my cells structure has to match access very closely to work.

private void btnImport_Click(object sender, EventArgs e)
    {
        DialogResult dr = MessageBox.Show(
            "Warning: when importing data into the Access database, ensure that the field columns match Access's fields or the file may become corrupt. Do you still wish to proceed?","Import caution",
            MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
        if (dr == DialogResult.OK)
        {
            try
            {

                using (OleDbConnection conn = new OleDbConnection(Con))
                {
                    using (OleDbCommand cmd = new OleDbCommand())
                    {
                        cmd.Connection = conn;
                        conn.Open();
                        cmd.CommandText =
                                "Insert INTO ACTB (FirstName, LastName, GrossIncome, LessTNT, TaxableIncomeCE, TaxableIncomePE, GrossTaxableIncome, LessTE, LessPPH, NetTax, TaxDue, HeldTaxCE, HeldTaxPE, TotalTax, PersonID) " +
                                "VALUES(@First, @Last, @Gross, @LessTNT, @TCI, @ADDTI, @GTI, @LessTE, @LessPPH, @LessNTI, @TD, @TWCE, @TWPE, @TATW, @PersonID)";
                        for (int s = 0; s < DGVExcel.Rows.Count - 1; s++)
                        {
                            cmd.Parameters.Clear();
                            //cmd.Parameters.AddWithValue("@ID", Convert.ToInt32(txtID.Text));
                            cmd.Parameters.AddWithValue("@First", DGVExcel.Rows[s].Cells[0].Value);
                            cmd.Parameters.AddWithValue("@Last", DGVExcel.Rows[s].Cells[1].Value);
                            cmd.Parameters.AddWithValue("@Gross", Convert.ToDouble(DGVExcel.Rows[s].Cells[2].Value));
                            cmd.Parameters.AddWithValue("@LessTNT",
                                Convert.ToDouble(DGVExcel.Rows[s].Cells[3].Value));
                            cmd.Parameters.AddWithValue("@TCI", Convert.ToDouble(DGVExcel.Rows[s].Cells[4].Value));
                            cmd.Parameters.AddWithValue("@ADDTI", Convert.ToDouble(DGVExcel.Rows[s].Cells[5].Value));
                            cmd.Parameters.AddWithValue("@GTI", Convert.ToDouble(DGVExcel.Rows[s].Cells[6].Value));
                            cmd.Parameters.AddWithValue("@LessTE", Convert.ToDouble(DGVExcel.Rows[s].Cells[7].Value));
                            cmd.Parameters.AddWithValue("@LessPPH",
                                Convert.ToDouble(DGVExcel.Rows[s].Cells[8].Value));
                            cmd.Parameters.AddWithValue("@LessNTI",
                                Convert.ToDouble(DGVExcel.Rows[s].Cells[9].Value));
                            cmd.Parameters.AddWithValue("@TD", Convert.ToDouble(DGVExcel.Rows[s].Cells[10].Value));
                            cmd.Parameters.AddWithValue("@TWCE", Convert.ToDouble(DGVExcel.Rows[s].Cells[11].Value));
                            cmd.Parameters.AddWithValue("@TWPE", Convert.ToDouble(DGVExcel.Rows[s].Cells[12].Value));
                            cmd.Parameters.AddWithValue("@TATW", Convert.ToDouble(DGVExcel.Rows[s].Cells[13].Value));
                            cmd.Parameters.AddWithValue("@PersonID", (DGVExcel.Rows[s].Cells[14].Value));
                            cmd.ExecuteNonQuery();
                            Console.WriteLine(s);
                        }
                    }

                }
            }
            catch (OleDbException ex)
            {
                MessageBox.Show("Import error: " + ex);
            }
            finally
            {
                Restore();
            }

        }
    }


texts:
Inspired by a question on SO I was checking how to calculate the cube root of an integer and found a C-ish solution on Hacker's Delight:

// Program for computing the integer cube root.
// Max line length is 57, to fit in hacker.book.
#include <stdio.h>
#include <stdlib.h>     //To define "exit", req'd by XLC.

// Execution time is 3 + (11 + mul)11 = 124 + 11*mul (avg) cycles.
// ------------------------------ cut ----------------------------------
int icbrt1(unsigned x) {
   int s;
   unsigned y, b;

   y = 0;
   for (s = 30; s >= 0; s = s - 3) {
      y = 2*y;
      b = (3*y*(y + 1) + 1) << s;
      if (x >= b) {
         x = x - b;
         y = y + 1;
      }
   }
   return y;
}

I tried to adapt this to Common Lisp and came up with this:

(defun icbrt (x)
  "Returns the integer cube root of X."
  (assert (plusp x) (x) "Please provide a positive integer! ~D < 0" x)
  (loop for s downfrom 30 to 0 by 3
        for y of-type integer = 0 then (* 2 y)
        for b of-type integer = (ash (1+ (* 3 y (1+ y))) s)
        when (>= x b)
        do (incf y)
           (setf x (- x b))
        finally (return y)))

While it works I am still wondering if it could be express more idiomatic. I am especially unsure about the setf within the loop construct.

Any comment is gratefully acknowledged.


texts:
It has been mentioned in the Clojure Style guide to avoid functions longer than 10 SLOC but mine has more than 10 (47 to be exact).

The code is an web api implementation and follows like this:

(defn classify
  "Sends a text to a classifier and returns a classification"
  [keys texts classifier & user-name]
  {:pre [(check-keys? keys)]}
  (let [textbase64-tag (map #(make-xml-node :textBase64
                                            {:id (str "Text" (str (index-of % texts)))}
                                            (String. (encode (.getBytes %)) )) texts)
        texts-tag (make-xml-node :texts {} textbase64-tag)
        user-attribute (if (> (count user-name) 0)
                         { :username (first user-name) })
        classify-tag (if (= (count user-name) 0)
                       (map #(make-xml-node :classify
                                            {:id (str "Classify" %)
                                             :classifierName classifier
                                             :textId (str "Text" %)
                                             })
                            (range (count texts)))
                       (map #(make-xml-node :classify
                                            {:id (str "Classify" %)
                                             :classifierName classifier
                                             :textId (str "Text" %)
                                             :username (first user-name)})
                            (range (count texts))))
        read-calls (make-xml-node :readCalls
                                  {:readApiKey (keys :read-key)}
                                  classify-tag)
        uclassify-response (raw-post-request
                            (xml/emit-str
                             (xml-append-elements uclassify
                                                  (list texts-tag read-calls))))]
    (if (check-response
         (get-response uclassify-response))
      (readable-list
       (list
        (x/xml-> uclassify-response
                 :readCalls :classify
                 :classification (x/attr :textCoverage))
        (map vector
             (x/xml-> uclassify-response
                      :readCalls :classify
                      :classification :class
                      (x/attr :className))
             (x/xml-> uclassify-response
                      :readCalls :classify
                      :classification :class
                      (x/attr :p)))))
      false ;; Will never reach here
      )))

The code initially builds all the associated xml tags within let and after building them sends a request to the server and then checks out the response to see if it succeeded.

Why I didn't handle the response in a separate function is because that it won't be reused again. Is this a good practice, any suggestions ?


texts:
def bfs(graph, root):
    visited, queue = [], [root]
    while queue:
        vertex = queue.pop(0)
        for w in graph[vertex]:
            if w not in visited:
                visited.append(w)
                queue.append(w)

graph = {0: [1, 2], 1: [2], 2: []}
bfs(graph, 0)

Does this look like a correct implementation of BFS in Python 3?


texts: Speed Efficiency of Decompression Algorithm

texts:
I've rewritten a piece of Javascript in Python 3.7 that decompresses a file compressed in a specific format. The project that I got this from is available here.
The code I've come up with is as close an analog as I could interpret (I'm not the best at Javascript).
def decompress_lz2(data):
    global loop_count
    lb_len = 0
    lb_dist = 0
    escape = 0x16

    off_input = 0

    output = b''

    while off_input < len(data):
        loop_count += 1
        if lb_len:
            off_output = len(output) - lb_dist

            repeat = max(0, off_output + lb_len - len(output))

            chunk = output[off_output:off_output + lb_len - repeat]
            output += chunk

            if repeat:
                repeat_chunk = bytes([chunk[-1]]) * repeat
                output += repeat_chunk

            lb_len = 0

        if escape:
            chunk = data[off_input:off_input + escape]
            output += chunk
            off_input += escape
            escape = 0

        flag = data[min(off_input, len(data) - 1)]
        off_input += 1

        lb_len = flag >> 5

        if lb_len:
            if lb_len == 7:
                while True:
                    next_ = data[off_input]
                    off_input += 1
                    lb_len += next_
                    if next_ != 0xff:
                        break

            lb_len += 2

            lb_dist = (flag & 0x1F) << 8
            lb_dist += (1 + data[off_input])
            off_input += 1

            if lb_dist == 0x2000:
                lb_dist += (data[off_input] << 8)
                off_input += 1
                lb_dist += data[off_input]
                off_input += 1

        else:
            escape = flag + 1

    return output

where data is a byte string read in from a file opened in binary mode. My code and the original code both produce the same output, but where the original code takes only a few seconds to execute, mine takes ~10 minutes on the same file. Testing with multiple files yields similar benchmarks. My specific efficiency question is: What can I do to increase the speed of execution of this script on the same system while maintaining output accuracy?
I'm open to the idea of multithreading/multiprocessing though I don't think it's possible due to the nature of this compression type.
Example file, though it's very small and runs quickly on both implementations. It must be fed to decompress_lz2 as bytes.