texts:
I was wondering if anyone could give a critique of my code. We are supposed to be using inheritance and OOP principles. All the functions but the PlayerSet class were given, so really I just need someone to critique that class.

The full code is here.

class PlayerSet:
    '''A group of players to play
    the Pass The Pigs game.'''

    def __init__(self,playerCount):
        '''PlayerSet(int) -> PlayerSet
        Contstructs a group of players,
        given how many there are and asks the
        name of each player.'''
        self.playerCount = playerCount # initialize count of players attribute
        self.playersList = [] # initialize list of players attrbute
        for i in range(1,self.playerCount+1): # for every i between 1 and plyerCount
            name = input('Player ' + str(i) + ', please enter your name:') # ask player i's name
            player = Player(name) # create a player with that name
            self.playersList.append(player) # add the player to the list of players
        self.currentPlayer = self.playersList[0] # initialize current player attribute

    def __str__(self):
        '''print(PlayerSet) -> str
        Returns all of the player's
        name and score.'''
        string='' # will contain output
        for player in self.playersList: # for every player in the list of players
            string+= player.get_name() + ' has ' + str(player.get_score()) + ' points \n' # add a string saying the player's name and current score
        return string # return the string

    def get_curr_name(self):
        '''PlayerSet.get_curr_name() -> str
        Returns the name of the current player.'''
        return self.currentPlayer.get_name() # return the name of the player

    def go_to_next_player(self):
        '''PlayerSet.go_to_next_player()
        Moves the current player to the next
        player.'''
        index = 0 # will contain index of the current player
        for i in range(len(self.playersList)): # for every index in list of players
            if self.playersList[i] == self.currentPlayer: # if that index is correct
                index = i # assign index to the desired index

        index += 1 # add 1 to the desired index, we want to move to next player
        index %= self.playerCount # if the number of the player goes over, take the residue mod playerCount
        self.currentPlayer=self.playersList[index] # make the current player equal to the new index of the list of players

    def is_curr_winner(self):
        '''PlayerSet.is_curr_winner() -> bool
        Returns if the current player has won.'''
        if self.currentPlayer.get_score() >= 100: # if the current player has won
            return True
        else: # otherwise
            return False

    def take_turn(self):
        '''PlayerSet.take_turn()
        Takes the player's turn.'''
        self.currentPlayer.play_turn() # use player's method - play_turn() which plays a turn

    def play_game(self):
        '''PlayerSet.play_game()
        Plays the real Pass The Pigs game! Woohoo!'''
        while self.is_curr_winner() == False: # until a player has won
            print(self) # print the status of the players
            print(self.get_curr_name() + ", it's your turn") # print whose turn it is
            self.take_turn() # take the player's turn
            if self.is_curr_winner() == True: # if the current player has won
                print(self) # print the status of the players
                return self.get_curr_name() + ' has won!' # return which player has won
            self.go_to_next_player() # go to the next player


texts: Change the background color of each section of the page when the user scrolls

texts:
I want to change the background color of each section of the page when the user scrolls. The code works but I feel like it's too inefficient

var colors = ['blue','yellow','green','purple','brown'];
var myScope;
var sections = [$('#section1'),$('#section2'),$('#section3'),$('#section4'),$('#section5')];
var sectionTop = [$('#section1').offset().top, $('#section2').offset().top, $('#section3').offset().top, $('#section4').offset().top, $('#section5').offset().top];
var zeus;

$(window).scroll(function () {
myScope = $(window).scrollTop() + 300;

    if (myScope >= sectionTop[0]  && myScope < sectionTop[1]) {
    sections[0].css('background-color', colors[0]);
    } else {
    sections[0].css('background-color', 'white');
    };

    if (myScope >= sectionTop[1]  && myScope < sectionTop[2]) {
    sections[1].css('background-color', colors[1]);
    } else {
    sections[1].css('background-color', 'white');
    };

    if (myScope >= sectionTop[2]  && myScope < sectionTop[3]) {
    sections[2].css('background-color', colors[2]);
    } else {
    sections[2].css('background-color', 'white');
    };

    if (myScope >= sectionTop[3]  && myScope < sectionTop[4]) {
    sections[3].css('background-color', colors[3]);
    } else {
    sections[3].css('background-color', 'white');
    };

    if (myScope >= sectionTop[4] ) {
    sections[4].css('background-color', colors[4]);
    } else {
    sections[4].css('background-color', 'white');
    };

});

I also tried to replace all those "if" with a "for" loop but it doesn't work, it doesn't pop any errors or anything, it just doesn't work.

for (var i = 0; i < sections.length-1; i++) {
        var j = i++;
        if (myScope >= sectionTop[i] && myScope < sectionTop[j]) {
        sections[i].css('background-color', colors[i]);
        } else {
        sections[i].css('background-color', 'white');
        };
    };


texts: Pandas updating/adding columns to rows incrementally using dictionary key values

texts:
I want to populate columns of a dataframe (df) by iteratively looping over a list (A_list) generating a dictionary where the keys are the names of the desired columns of df (in the example below the new columns are 'C', 'D', and 'E')

import pandas
def gen_data(key):
    #THIS FUNCTION IS JUST AN EXAMPLE THE COLUMNS ARE NOT NECESSARILY RELATED OR USE THE KEY
    data_dict = {'C':key+key, 'D':key, 'E':key+key+key}
    return data_dict

A_list = ['a', 'b', 'c', 'd', 'f']
df = pandas.DataFrame({'A': ['a', 'b', 'c', 'd', 'f'], 'B': [1,2,3,3,2]})

for A_value in A_list:
    data_dict = gen_data(A_value)
    for data_key in data_dict:
        df.loc[df.A == A_value, data_key] = data_dict[key]

So the result of this should be:

df = pandas.DataFrame({'A': ['a', 'b', 'c', 'd', 'e','f'],
                       'B': [1,2,3,3,2,1],
                       'C': ['aa','bb','cc','dd',nan,'ff'],
                       'D': ['a', 'b', 'c', 'd', nan,'f'],
                       'E': ['aaa','bbb','ccc','ddd',nan,'fff']})

I feel that

for data_key in data_dict:
    df.loc[df.A == A_value, data_key] = data_dict[key]

is really inefficient if there are a lot of rows in df and I feel that there should be a way to remove the for loop in this code.

for A_value in A_list:
    data_dict = gen_data(A_value)
    for data_key in data_dict:
        df.loc[df.A == key, data_key] = data_dict[key]


texts: Jquery improvement of this script - Adding and removing items from list

texts:
I've been getting help with this script seen below. It allows one input box to be used to put values into a text area and also display a list of the items. The items can be deleted once inserted:

http://jsfiddle.net/ZTuDJ/50/

// If JS enabled, disable main input
$("#responsibilities").prop('disabled', true);
// $("#responsibilities").addClass("hidden");

// If JS enabled then add fields
$("#resp").append('<input placeholder="Add responsibility" id="resp_input" ></input><input type="button" value="Add" id="add"> ');

// Add items to input field
var eachline='';
$("#add").click(function(){
    var lines = $('#resp_input').val().split('\n');
    var lines2 = $('#responsibilities').val().split('\n');
    if(lines2.length>10)return false;
    for(var i = 0;i < lines.length;i++){
        if(lines[i]!='' && i+lines2.length<11){
        eachline += lines[i] + '\n';
        }
    }

    $('#responsibilities').text($("
" + eachline + "
").text()).before("
"+$("
"+lines+"
").text()+"Remove
");

    $('#resp_input').val('');
});

$(document).on('click', '.right a', function(){
    var el = $(this).closest('li')
    var index = $('li').index(el);
    var text = eachline.split('\n');
    text.splice(index, 1);
    eachline = text.join('\n')
    $('#responsibilities').text(eachline)
    el.remove()
})

I was wondering if it would be possible to tag links in the list with the following information:

Remove

By tagging the links in this way I was thinking I could easily point to them with jquery if I wanted to delete it or later edit it.

Is there room to simplify this script in this way?


texts: Convert generic class into XML string of specific structure

texts:
There is a need to have a specific structure of XML string when interacting with 3rd party system. Here are two examples:

<DocumentElement>
 <Country>
  <CountryCode>UA</CountryCode>
  <Name>Ukraine</Name>
 </Country>
</DocumentElement>

and

<DocumentElement>
 <Currency>
  <CurrencyCode>UAH</CurrencyCode>
  <Description>Hryvnia</Description>
 </Currency>
</DocumentElement>

Like you can see it is a common wrapping tag DocumentElement.
So, here is approach #1:

Have a wrapper class:

[XmlRoot("DocumentElement")]
public class DocumentElement<T>
{
    public T InnerObject { get; set; }

    public DocumentElement(){}
    public DocumentElement(T some)
    {
        InnerObject = some;
    }
}

And replace InnerObject after conversion:

public static string GetXml<T>(T instance) where T : class
{
    var wrapper = new DocumentElement<T>(instance);
    var writer = new StringWriter();
    var serializer = new XmlSerializer(typeof(DocumentElement<T>));
    serializer.Serialize(writer, wrapper);
    return writer.ToString().Replace("InnerObject", instance.GetType().Name);
}

Or, approach #2:

Throw away DocumentElement and just concat a needed string:

public static string GetXml<T>(T instance) where T : class
{
    var writer = new StringWriter();
    var serializer = new XmlSerializer(typeof(T));
    serializer.Serialize(writer, instance);
    return "<DocumentElement>" + writer.ToString() + "</DocumentElement>";
}

Both approaches produce a needed format but neither looks clean enough.
Maybe, someone can suggest a better approach to this?


texts:
I recently wrote my first webapp and here is the code. I want to make it better, but I'm not exactly sure how.  I believe the first place I should start is with the structure of it. Is this spaghetti code? If yes, how do I change that? You can view it at http://shiftfrog.com

I created a class called 'doer' that basically drives the program. Is that wrong? Should my class be called calendar and then manipulate in my post call to /calendar?

class Doer

  def makeDate(date)
    return Date.strptime(date, "%m/%d/%Y")
  end

  def buildArray(dateObj, on, off)
    array = frontpadding(dateObj, on, off)
    month = dateObj.month
    newMonth = month
    day = dateObj.mday
    date = dateObj
    while month == newMonth
      temp_array = [day,'day']
      array.push(temp_array)
      day = day + 1
      date = date + 1
      newMonth = date.month
    end
    endpadding(date, array)
    array
  end

  def endpadding(dateObj, array)
    dofw = dateObj.wday
    filler = (dofw - 6).abs + 1
    if filler == 7
      #do nothing
    else
      until filler == 0
        temp_array = ['','day']
        array.push(temp_array)
        filler = filler - 1
      end
    end
  end

  def frontpadding(dateObj, on, off)
    array = Array.new
    day = dateObj.mday
    firstOfMonth = Date.new(dateObj.year, dateObj.month)
    filler = firstOfMonth.wday
    on = on.to_i
    off = off.to_i
    mod = on + off
    if day != 1
      @days = day
      @location = @days + filler
      until day <= 1
        off.times do
          if day > 1
            temp_array = ['','day']
            array.unshift(temp_array)
            day = day - 1
          end
        end
        on.times do
          if day > 1
            temp_array = ['','dayOn']
            array.unshift(temp_array)
            day = day - 1
          end
        end
      end
    end
    until filler == 0
        temp_array = ['','day']
        array.unshift(temp_array)
        filler = filler - 1
    end
    array
  end

  def backFill(cal, on, off)
    @location = @location.to_i
    if @location > 0
      @location = @location - 1
      until @days == 0
        cal[0][1][@location][0] = @days
        @days = @days - 1
        @location = @location - 1
      end
    end
    cal
  end

  def makeCal(date, on, off)
    dateObj = makeDate(date)

    @cal = Array.new
    months = 0
    while months < 13
    #   #pass dateobj to build array
      array = buildArray(dateObj, on, off)
    #   #save array to hash with month key
      monthName = Date::MONTHNAMES[dateObj.mon]
      monthYear = "#{monthName} " + dateObj.year.to_s
      holder = Array.new
      holder.push monthYear
      holder.push array
      @cal.push holder
    #   #create new date object using month and set it to the first
      dateObj = Date.new(dateObj.year, dateObj.month)
      dateObj >>= 1
      months = months + 1
    end
    @cal = createCal(@cal, on, off)
    @cal = backFill(@cal, on, off)
  end

  def createCal(cal, on, off)
    on = on.to_i
    off = off.to_i
    @mod = on + off
    daycount = 0
    cal.each do |month|
      month[1].each do |day|
        if day[0] == ''
          #do nothing
        else
          if daycount % @mod < on
            day[1] = 'dayOn'
          end
          daycount = daycount + 1
        end
      end
    end
    cal
  end
end

get '/' do
  haml :ask
end

post '/calendar' do
  @on = params["on"]
  @off = params["off"]
  @date = params["date"]

  a = Doer.new
  @cal = a.makeCal(@date, @on, @off)
  haml :feeling
end


texts:
I'm writing the data structures for my program (a toy compiler), and I'm trying to understand what's the best way to define the AST:

Current code

data RExpr = RExpr Location InnerRExpr
data InnerRExpr = RLExpr LExpr | RConstant Constant | RMathExpr MathExpr | FCall Id [RExpr]

Alternative A

data RExpr = RLExpr Location LExpr
           | RConstant Location Constant
           | RMathExpr Location MathExpr
           | FCall Location Id [RExpr]

Alternative B

data RExpr = RLExpr { loc::Location, getLexpr::LExpr}
           | RConstant { loc::Location, getConstant::Constant}
           | RMathExpr { loc::Location, getExpr::MathExpr}
           | FCall { loc::Location, id::Id, params::[RExpr] }

Honestly I'm not satisfied with either of the three options, because the current code means that I have an extraneous object in the AST which doesn't really mean anything, alternative A means that I have to pattern match every time I want to extract the location (or write a boilerplate function that does it) and alternative B means cluttering the global namespace with functions whose names are likely to collide.

Suggestions?


texts: Egg drop problem solution in template meta-programming

texts:
I have implemented a dynamic programming solution of the egg-dropping problem (this problem, but generalized for any number of eggs and floors):

#include <iostream>
#include <limits.h>

//Optimal sub-structure
//We have K floor and N eggs
//Case1: If egg break of X floor then we have x - 1 floor and N - 1 egg
//Case2: If egg doesn't break at X floor then we have K - X floor and N eggs
//Base Case1: we have 1 egg then answer is K floor
//Base Case2: we have 0 or 1 floor then 0 or 1 is answer

int cache[1234][1234];

int solve(int egg, int floor) {

    if(floor == 0 || floor == 1 || egg == 1)
        return floor;

    if(cache[egg][floor])
        return cache[egg][floor];

    int result = INT_MAX;
    for(int current_floor = 1; current_floor <= floor; ++current_floor) {
        int local = std::max(solve(egg - 1, current_floor - 1), solve(egg, floor - current_floor));
        if(local < result)
            result = local;
    }

    cache[egg][floor] = 1 + result;
    return cache[egg][floor];
}

int main(void) {

    int egg = 0, floor = 0;
    //egg = 2, floor = 10 result = 4
    std::cin >> egg >> floor;
    std::cout << "result is: " << solve(egg, floor) << '\n';

    return 0;
}

Now I want to implement this solution in C++ template meta-programming, but I am really not getting how I can use the result variable from the solve function to the loop function.

#include <iostream>
#include <climits>

template<int egg, int floor>
struct solve;

template<int current_floor, int egg, int floor>
struct loop {
    static const int r1 = solve<egg - 1, current_floor - 1>::result;
    static const int r2 = solve<egg, floor - current_floor>::result;
    static const int local = r1 > r2 ? r1 : r2;
    //Here I have to compare this local variable to result variable of the
    //solve class and store?
    //In other words I have to implement
    //if(local < result)
    //  result = local
    loop<current_floor + 1, egg, floor> l;
};

template<int current_floor, int egg>
struct loop<current_floor, current_floor, egg> {
    static const int r1 = solve<egg - 1, current_floor - 1>::result;
    static const int r2 = solve<egg, floor - current_floor>::result;
    static const int local = r1 > r2 ? r1 : r2;
};

template<int egg, int floor>
struct solve {
    static const int result = loop<1, egg, floor>::result + 1;
};

template<int egg>
struct solve<egg, 0> {
    static const int result = 0;
};

template<int floor>
struct solve<1, floor> {
    static const int result = floor;
};

int main(int argc, char** argv) {
    //main function to check program
    return 0;
}


texts: Calculating COUNT(*) of a MAX() + GROUP BY query

texts:
I have a SELECT query I'm executing which has a MAX() column and a GROUP BY clause, and in addition to the results of this query that I need to return to the client, I also need to return the total count of all results as well.
Essentially my query is this:
SELECT id, col1, col2, MAX(col3) as col3
FROM tbl
GROUP BY col1, col2

It'll usually have a WHERE clause too.
When returning this data to the client, I also specify LIMIT and OFFSET clauses to limit the number of results being retrieved and displayed on the UI at one time. For a good UX, I also return and display the total number of results that the above SELECT query would produce if it didn't have the LIMIT and OFFSET clauses, so that the UI can display e.g. "41-60 of 6500 results".
Currently, I use a WITH temporary table to get what I want:
WITH temp AS (
    SELECT id, col1, col2, MAX(col3) as col3
    FROM tbl
    GROUP BY col1, col2
)
SELECT COUNT(*) FROM temp

But I'm concerned about the efficiency of this. The sans-LIMIT-and-OFFSET query could return hundreds of thousands of rows, so I'm thinking that the WITH approach to getting the total count isn't the best way to do this.
Is there a more efficient way, which I'm not thinking of? Either a more efficient way to get the COUNT I need or some thoughts on reusing a previous COUNT value?

Example data
Assume this is the data in my table:
id   col1  col2  col3
______________________
1     5     8     30
2     5     8     33
3     5     9     40
4     6     8     30
5     6     8     31
6     6     8     32
7     6     9     39
8     7     8     33
9     7     8     32
10    8     8     34

So my SELECT query would return this (assume the client specified LIMIT 4 OFFSET 0):
SELECT id, col1, col2, max(col3) as col3
FROM tbl
GROUP BY col1, col2
LIMIT 4
OFFSET 0;
    id   col1  col2  col3
    ______________________
    2     5     8     33
    3     5     9     40
    6     6     8     32
    7     6     9     39

And then I'd use that query without the LIMIT and OFFSET clauses as a subquery and SELECT COUNT(*) from it, which would return 6, and I'd return both the 6 and the results to the client. The client runs this query automatically every 10 or so seconds to keep the UI refreshed, and every time the client presses the arrows at the bottom of the table on the UI to go to the next page (i.e. specify a new OFFSET).

The exact schema of this stripped-down case is this:
CREATE TABLE test (id INT NOT NULL, col1 TEXT, col2 TEXT, col3 INT, PRIMARY KEY (id));

The only difference between my schema and this is that I also join on another table based on the id, and there are more than just 2 columns in the GROUP BY clause. I kept this example minimal because the WITH part is what's really important here.

EXPLAIN reports that it's indeed creating a temporary table of all 10 rows, hence my concern:
> EXPLAIN WITH temp AS ( SELECT id, col1, col2, MAX(col3) AS col3 FROM test GROUP BY col1, col2 ) SELECT COUNT(*) FROM temp;
+------+-------------+------------+------+---------------+------+---------+------+------+---------------------------------+
| id   | select_type | table      | type | possible_keys | key  | key_len | ref  | rows | Extra                           |
+------+-------------+------------+------+---------------+------+---------+------+------+---------------------------------+
|    1 | PRIMARY     | <derived2> | ALL  | NULL          | NULL | NULL    | NULL |   10 |                                 |
|    2 | DERIVED     | test       | ALL  | NULL          | NULL | NULL    | NULL |   10 | Using temporary; Using filesort |
+------+-------------+------------+------+---------------+------+---------+------+------+---------------------------------+


texts: Design patterns: choosing the right handler depending on data type

texts:
Suppose we have an application which process packets from somewhere. We should choose right handler for the packet depending on packet type and also we know that it might be necessary to change algorithm of handlers and add new handlers in the future.

The question is: how can I write maintainable code?

Here is my draft. I'm sure there should be patterns for this and similar tasks. I want to resolve not only my small task but read deep about design and patterns which developers usually use in this case. What do you recommend for me?

public class RequestHandler
{
    Dictionary<string, IDocumentProcessor> _handlers;

    public Dictionary<string, IDocumentProcessor>  Handlers { get { return _handlers; } }

    public RequestHandler(IDictionary<string, IDocumentProcessor> handlers)
    {
        _handlers = handlers.ToDictionary(key => key.Key, val => val.Value);
    }

    public void Handle(Document document)
    {
        IDocumentProcessor handler;
        handler = Handlers.ContainsKey(document.Type)? Handlers[document.Type] : null;

        if(handler == null) throw new Exception();

        Task task = Task.Factory.StartNew( () => handler.Process(document) );
    }
}

public interface IDocumentProcessor
{
    void Process(Document document);
}

public class DocumentAProcessor:IDocumentProcessor
{
    public void Process(Document document)
    {

    }
}

public class DocumentBProcessor:IDocumentProcessor
{
    public void Process(Document document)
    {

    }
}


texts:
I have a class Accounts with an array of account numbers and an array of balances I have a member function add_acc that adds an account. But before adding an account, I want to check if the account no. to be added, already exists or not. If it exists then an error message is displayed else the new account is added. In my following class design, the compiler is not able to check for the uniqueness of the account no. when more than 1 accounts are being added. Following is my approach.
#include <iostream>
#include <stdlib.h>
using namespace std;
#define MAX 100
class Account
{
    long long int acc_no[MAX];
    long long int balance[MAX];
    int count;
    public :
        void CNT()
        {
            count=0;
        }
        void add_acc();

};
void Account::add_acc()
{
    if(count==0)
    {
        cout<<"Enter the account number"<<" : ";
        cin>>acc_no[count];
        cout<<"Enter the balance"<<" : ";
        cin>>balance[count];
    }
    else
    {
        long long int temp;
        cout<<"Enter the account no. to be added : ";
        cin>>temp;
        for(int i=0;i<count;i++)
        {
            if(temp==acc_no[i])
            {
                cout<<"Account no. already exists"<<"\n";
                return;
            }
            else
            {
                continue;
            }

        }
        temp=acc_no[count];
        cout<<"Enter the balance : ";
        cin>>balance[count];

    }
    count++;
}
int main()
{
    Account A;
    A.CNT();
    char ch;
    while(ch)
    {
        A.add_acc();
        cout<<"Want to add another account? : ";
        cin>>ch;
        if(ch=='Y' || ch=='y')
            continue;
        else
            break;
     }
    return 0;
}

The problem with my output -:
In the first run I entered the account no. as 123, int the second run I enter the acc. no. as 345 and when in the third run again I entered the acc. no. as 345, the error message was not displayed.


texts: Implementing linked list from scratch - Follow up

texts:
A follow up for this question:
Implementing Linked lists in Python from scratch

Node:

class Node():
    def __init__(self, key):
        self.key = key
        self.next = None

Linked list:

from node import Node

class LinkedList:
    link_connection = ' -> '

    ''' init, getters, setters '''
    def __init__(self, key):
        self.head = Node(key)
        self.tail = self.head
        self.length = 1

    @property
    def head(self):
        return self.__head

    @head.setter
    def head(self, node):
        if node is not None:
            self.__head = node

    @property
    def tail(self):
        return self.__tail

    @tail.setter
    def tail(self, node):
        if node is not None:
            try:
                if node.next is None:
                    self.__tail.next = node
                    self.__tail = self.__tail.next
            except AttributeError:
                self.__tail = node

    @property
    def length(self):
        return self.__length

    @length.setter
    def length(self, value):
        self.__length = value

    ''' generator for nodes '''
    ''' iterating, search etc. '''
    def node_generator(self, target=None):
        node = self.head
        yield node
        while node.next is not None and node.next.key != target:
            node = node.next
            yield node

    def __iter__(self):
        return map(lambda node: node.key, self.node_generator())

    def __str__(self):
        return self.link_connection.join(str(key) for key in self)

    def go_forward(self, steps):
        for node in self.node_generator():
            if steps == 0:
                return node
            steps -= 1

    def delete(self, target):
        for node in self.node_generator(target):
            pass
        node.next = node.next.next
        self.length -= 1

    def __len__(self):
        return self.__length

    def append(self, key):
        node = Node(key)
        self.tail = node
        self.length += 1

    def find(self, value):
        for node in self:
            if node == value:
                return node

Is this new implementation better?


texts: Slow performance in looping and filling missing data

texts:
I wrote some code that loops for specific data and then fills the missing cells in another sheet. The code works perfectly but it takes too much time to fill the missing cells (values).

What I tried to do is to Test if Cell B is blank or not , then I created 2 variables :

x for activesheet values which need to be filled and
y for sheet 1 (source) and keep comparing until x match y to take the value in front of the specific data.

The code I came up with:

  Sub TraiterNoms()
  Application.ScreenUpdating = False
  Application.DisplayAlerts = False
  Dim i As Variant
  Dim CompareRange As Variant
  Dim x As Variant
  Dim y As Variant
  Dim derlignE As Variant
  Dim derlignC As Variant

  derlignE = Range("A" & Rows.Count).End(xlUp).Row
  derlignC = Sheets("Feuil1").Range("B" & Rows.Count).End(xlUp).Row
  Set CompareRange = Sheets("Feuil1").Range("A:A").resize(derlignC, 1)

   For i = Range("A" & Rows.Count).End(xlUp).Row To 1 Step -1
    If Range("B" & i) = "" Then
      For Each x In Range("A:A").resize(derlignE, 1)
         For Each y In CompareRange
         If x = y Then x.Offset(0, 1) = y.Offset(0, 1)
        Next y
       Next x
      End If
    Next i
 Application.ScreenUpdating = True
 Application.DisplayAlerts = True
End Sub

I feel like I could improve this code to make it more fluent. Would that be over-complicated?

What's there to say about this code?


texts: Improving interactive component performance with constant image translation

texts:
I am making this React Component for an interactive eye that moves and tracks the user's mouse cursor wherever it goes to in the webpage. However, I faced 3 problems while doing so.

The eye moves as if the eye is in the middle of the webpage, so that when I place the eye somewhere other than the center of the webpage, it does not look at the cursor, only follow its movements.

Everytime I move my mouse in the webpage vigorously, my CPU usage rose to about 10% and my GPU rose 30%. Is this normal for interactive websites?

The image blurs sometimes after, when, and before moving.

Here is my Eye Component:
import React, { Component } from "react";
import "./Eye.css";
import pupil from "../assets/images/pupil.png";
import eyelid from "../assets/images/eye.png";

class Eye extends Component {
  componentDidMount() {
    window.addEventListener("mousemove", this._onMouseMove);
    window.addEventListener("mouseout", this._onMouseLeave);
  }

  _onMouseMove = (e) => {
    var balls = document.getElementsByClassName("ball");

    var x = (e.clientX * 100) / window.innerWidth + "%";
    var y = (e.clientY * 100) / window.innerHeight + "%";

    console.log(e.clientX, e.clientX);

    balls[0].style.left = x;
    balls[0].style.top = y;
    balls[0].style.transform = "translate(-" + x + ",-" + y + ")";
    balls[0].style.transitionDuration = "0s";
  };

  _onMouseLeave = (e) => {
    var balls = document.getElementsByClassName("ball");

    var x = "50%";
    var y = "50%";

    balls[0].style.left = x;
    balls[0].style.top = y;
    balls[0].style.transform = "translate(-" + x + ",-" + y + ")";
    balls[0].style.transitionDuration = ".5s";
  };

  render() {
    return (

    );
  }
}

export default Eye;

The Demo Problem HERE


texts:
So I wrote this simple program to place a certain number of people on a list of seats whilst maintaining maximum social distance.
Given that there is at least one empty seat, calculate the maximum.distance from an empty seat to the closest occupied seat and return the available seat.
How can this be improved to be better
// seats.cpp

#include <iostream>
#include <array>

constexpr int N = 50;

int traverse_right(const std::array<int, N> &seats, int i)
{
    if (i < 0)
        return 0;
    else if(seats[i] == 1)
        return i;
    else return traverse_right(seats, --i);
}

int traverse_left(const std::array<int, N> &seats, int i)
{
    if (i >= seats.size())
        return 0;
    else if(seats[i] == 1)
        return i;
    else return traverse_left(seats, ++i);
}

int get_available_seat(const std::array<int, N> &seats)
{
    int max = 0;
    int right_distance = 0;
    int left_distance = 0;
    int available_seat = -1;

    for(size_t i = 0; i != seats.size(); ++i)
    {
        if(seats[i] == 0)
        {
            right_distance = abs(i - traverse_right(seats, i));
            left_distance = abs(i - traverse_left(seats, i));
        }
        if(left_distance > max && right_distance > max)
        {
            if(left_distance <= right_distance && left_distance != 0)
                max = left_distance;
            else
                max = right_distance;
            available_seat = i;
        }
    }
    std::cout << "Maximum distance to available_seat is " << max << '\n';
    return available_seat;
}

void display(const std::array<int, N> &seats)
{
    for(const auto x : seats)
        std::cout << x << " ";
    std::cout << '\n';
}
int main()
{
    std::array<int, N> seats{};
    for(int i = 0; i < 12; ++i)
    {
        int available_seat  = get_available_seat(seats);
        seats[available_seat] = 1;
    }
    display(seats);
}

The code works as expected and though I didn't perform the check, user would need to test if there is an available seat before placing.


texts: Detecting Tic-Tac-Toe win: Enumerate all possibilities or use nested loops?

texts:
Currently I have a game that does this and then checks for victory conditions in victoryTable

victoryTable[0] = rows[0][0] + rows[0][1] + rows[0][2];
victoryTable[1] = rows[1][0] + rows[1][1] + rows[1][2];
victoryTable[2] = rows[2][0] + rows[2][1] + rows[2][2];
victoryTable[3] = rows[0][0] + rows[1][0] + rows[2][0];
victoryTable[4] = rows[0][1] + rows[1][1] + rows[2][1];
victoryTable[5] = rows[0][2] + rows[1][2] + rows[2][2];
victoryTable[6] = rows[0][0] + rows[1][1] + rows[2][2];
victoryTable[7] = rows[0][2] + rows[1][1] + rows[2][0];

But I am considering changing it to read this way:

for (int i = 0; i < 8; i++ ) {
    for (int n = 0; n < 3; n++) {
        for (int t = 0; t < 3; t++) {
            victoryTable[i] = rows[n][t] + // based on some combination of n,t and
                                       // if statement to filter out garbage/duplicates,
                                       // the more I think about this implementation the
                                       // more complicated it seems.
        }
    }
}

Would this be a step in the wrong direction?  It seems like I should put the things that change in a method or loop or something, but it also looks like this will make it harder to read what the code does, and have more potential for bugs (undesired conditions, etc) but also more expandability (if game board became larger in future version, for instance.

The larger context is this:  This is part of a method that determines the victory state of a Tic Tac Toe game.  In a 3x3 int[][], player X is represented by a 3, player O by a 30.  The code in this post adds each column, row, and diagonal, and stores them in an array.  Another method loops through that array and if any element equals 90, O wins, if it equals 9, X wins, otherwise nobody wins (yet).


texts: Fisher-Yates shuffle algorithm in javascript, modern and inside-out versions

texts:
I've implemented two different versions of the Fisher-Yates shuffle in javascript, and I'd like to know if I've made any mistakes.

I'm creating a deck of playing cards. I'm interested in these shuffle algorithms.

The object passed to the rng parameters below is a wrapper for Johannes Baagøe's Alea, a seedable PRNG that should produce a better sample of random numbers than built-in Math.random. Its API is the same as that of Math.random.

I am mostly wondering if I have made any fencepost errors or misunderstood the examples I'm referencing.

/** shuffle

    Shuffle an array.

    @see http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm

    @param {Array} array
    @param {Function} random Optional RNG. Defaults to Math.random.
    @return {Array} The original array, shuffled.
*/
function shuffle (array, random) {
  var i = array.length, j, swap;
  while (--i) {
    j = (random ? random() : Math.random()) * (i + 1) | 0;
    swap = array[i];
    array[i] = array[j];
    array[j] = swap;
  }
  return array;
}

/** pushRand

    Insert a value into an array at a random index. The element
    previously at that index will be pushed back onto the end.

    @see http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_.22inside-out.22_algorithm

    @param {Array} object to shuffle.
    @param {Mixed} value to insert.
    @param {Function} optional RNG. Defaults to Math.random.
    @return {Number} The new length of the array.

*/
function pushRand (array, value, random) {
  var j = (random ? random() : Math.random()) * array.length | 0;
  array.push(array[j]);
  array[j] = value;
  return array.length;
}

Here's a demo of the shuffle. Reloading the page does the inside-out shuffle, and clicking the face-down card does the modern shuffle.

Edit: I found a fencepost error in the "modern" version and fixed it here, but it's still in the demo. Not sure about the "inside-out" version yet.

Edit: I stopped being lazy and factored this stuff out, so it should easier to look at now. New demo up.

Edit: inside-out ver had the fencepost error too. It should look like this, I think:

function pushRand (array, value, random) {
  var j = (random ? random() : Math.random()) * (array.length + 1) | 0;
  array.push(array[j]);
  array[j] = value;
  return array.length;
}

Thanks, Paul!

Edit: Taking Adam's optimization suggestion into account, the new code looks like this:

/** shuffle

    Shuffle an array.

    @see http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_.22inside-out.22_algorithm

    @param {Array} array Array to shuffle.
    @param {Object} rng Optional RNG. Defaults to Math.
    @return {Array} The original array, shuffled.
*/
function shuffle (array, rng) {
  var i = array.length, j, swap;
  if (!rng) rng = Math;
  while (--i) {
    j = rng.random() * (i + 1) | 0;
    swap = array[i];
    array[i] = array[j];
    array[j] = swap;
  }
  return array;
}

/** pushRand

    Insert a value into an array at a random index. The element
    previously at that index will be pushed back onto the end.

    @see http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm

    @param {Array} array Array to insert into.
    @param {Mixed} value Value to insert.
    @param {Object} rng Optional RNG. Defaults to Math.
    @return {Number} The new length of the array.

*/
function pushRand (array, value, rng) {
  var j = (rng || Math).random() * (array.length + 1) | 0;
  array.push(array[j]);
  array[j] = value;
  return array.length;
}

Here's the updated editable demo (relevant code at the bottom).


texts: Finding the middle element of Singly Linked List

texts:
Here is my code:

    public void findMiddlePos() {
    int pos = 1;
    Node pointerOne = first;
    Node pointerTwo = first;
    while(pointerOne.next.next != null) {
        pointerOne = pointerOne.next.next;
        pointerTwo = pointerTwo.next;
        pos++;
    }
    System.out.println("The middle element is : ");
    if((pos % 2) == 1)
        pointerTwo.printNode();
    else
        pointerTwo.next.printNode();

}

Is it an efficient way? Also, I am doubtful about this line while(pointerOne.next.next != null). Previously, I was just using this condition in while loop: pointerOne.next != null, but I was getting Null pointer exception so shifter to earlier one.

Thanks.


texts: Writing a hyperlink to a cell with Apache POI

texts:
This code embeds a hyperlink into a cell of your choice of an Excel file.

/**
 * @param pathName  the path for the Excel file which you will update
 * @param string    the string you want to put in the cell, and if you put an empty string, it will default to
 *                  "Empty String"
 * @param hyperlink the hyperlink which will be embedded into the cell
 * @param row       the row number of the cell
 * @param column    the column number of the cell
 * @param firstTime this is used in case you want the file to be wiped and start from the beginning
 * @throws RuntimeException if the path can't be found or if an {@link IOException} is thrown for whatever reason
 */
public static void writeToCell(String pathName, String string, String hyperlink, int row, int column, boolean
        firstTime) {
    if (string.equals(""))
        string = "Empty String";

    if (!firstTime) {
        try {
            fileInputStream = new FileInputStream(new File(pathName));
        } catch (FileNotFoundException e) {
            throw new RuntimeException("File not found!", e);
        }
        try {
            workbook = new XSSFWorkbook(fileInputStream);
            sheet = workbook.getSheetAt(0);
        } catch (IOException e) {
            throw new RuntimeException("IOException thrown!", e);
        }
    } else {
        workbook = new XSSFWorkbook();
        sheet = workbook.createSheet();
    }

    CreationHelper createHelper = workbook.getCreationHelper();
    XSSFCell cell;
    try {
        cell = sheet.getRow(row).getCell(column, XSSFRow.CREATE_NULL_AS_BLANK);
    } catch (NullPointerException e) {
        try {
            cell = sheet.getRow(row).createCell(column);
        } catch (NullPointerException npe) {
            cell = sheet.createRow(row).createCell(column);
        }
    }
    XSSFHyperlink url = (XSSFHyperlink) createHelper.createHyperlink(XSSFHyperlink.LINK_URL);

    XSSFCellStyle hyperlinkStyle = workbook.createCellStyle();
    XSSFFont hlink_font = workbook.createFont();
    hlink_font.setColor(IndexedColors.BLUE.getIndex());
    hyperlinkStyle.setFont(hlink_font);

    url.setAddress(hyperlink);
    try {
        cell.setHyperlink(url);
    } catch (NullPointerException e) {
        cell.setCellType(XSSFCell.CELL_TYPE_STRING);
        cell.setHyperlink(url);
    }
    cell.setCellValue(string);
    cell.setCellStyle(hyperlinkStyle);

    try {
        if (fileInputStream != null)
            fileInputStream.close();
    } catch (IOException e) {
        throw new RuntimeException("IOException thrown!", e);
    }

    FileOutputStream fileOutputStream;
    try {
        fileOutputStream = new FileOutputStream(new File(pathName));
    } catch (FileNotFoundException e) {
        throw new RuntimeException("File not found!", e);
    }

    try {
        workbook.write(fileOutputStream);
        fileOutputStream.close();
    } catch (IOException e) {
        throw new RuntimeException("IOException thrown!", e);
    }
}

public static HyperlinkWriter newInstance(String pathName) {
    HyperlinkWriter writer = new HyperlinkWriter();
    try {
        fileInputStream = new FileInputStream(new File(pathName));
    } catch (FileNotFoundException e) {
        throw new RuntimeException("File not found!", e);
    }
    try {
        workbook = new XSSFWorkbook(fileInputStream);
        sheet = workbook.getSheetAt(0);
    } catch (IOException e) {
        throw new RuntimeException("IOException thrown!", e);
    }
    return writer;
}

I was wondering if there was a way to optimize this method in a way because I use this with a different class and I call upon this method multiple times but since I'm creating a FileInputStream and an XSSFWorkbook almost each time, I was wondering if there was a way to get around that and have the FileInputStream just add the bytes that it's missing, instead of reading the file from top to bottom almost each time the method is called. I should also mention that fileInputStream is static, so it won't be released from memory when the method ends (I think...)


texts:
I've just created a teeny little script to count the seconds until I get auto-logged off.  I already solved my issue with my ssh client settings, but I'd still like any help making the bash script nicer to read, or just tips in general.

#!/bin/bash

count=0
while ( [ : ] )
do
  count=$(($count+1))
  n=${n:-0}
  for i in `seq 0 $n`; do echo -en '\b'; done
  n="${#count}"
  echo -n $count
  sleep 1
done


texts: Coordinating Threads with Reactive Streams

texts:
I just started learning reactive streams with RxJava. After reading a couple of books and a lot of articles our there I am still having trouble understanding how to coordinate multiple threads.

I would appreciate a critique of the following code, particularly if anyone knows a better way to do it.

I basically want to execute multiple tasks in the background, and as results start to get back I want to get immediately notified of the results. I want the background tasks to run in individual threads, but I want the notification thread to run in a single thread.

My idea is that the notification code does not need to worry about synchronization and I can achieve that by making sure the notification code only runs in one thread.

This was my best attempt of that:

public class Question {

    public static void main(String[] args) {

        //A hypothetical list of tasks to run asynchronously
        List<Callable<String>> tasks = Arrays.asList(
            () -> "One: " + Thread.currentThread().getName(),
            () -> "Two: " + Thread.currentThread().getName(),
            () -> "Three: " + Thread.currentThread().getName()
        );

        //A blocking queue to hold the results when ready
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(3);

        //when a task is done, this observer puts it in the queue.
        //observer code then will run in the currently processing thread
        Observer<String> observer = Observers.create(queue::offer);
        tasks.stream().map(Question::async).forEach(result -> result.subscribe(observer));

        //as tasks get resolve and enter the queue, this other observer process the results
        //in my current thread, not in any of the task threads.
        consumer(queue, 3).forEach(item -> {
                System.out.println("Received " + item + " at " + Thread.currentThread().getName());
            });
    }

    static <T> Observable<T> async(Callable<T> supplier) {
        return Observable.<T>create(subscriber -> {
            try {
                subscriber.onNext(supplier.call());
                subscriber.onCompleted();
            }
            catch (Exception ex) {
                if (!subscriber.isUnsubscribed()) {
                    subscriber.onError(ex);
                }
            }
        }).subscribeOn(Schedulers.computation());
    }

    static <T> Observable<T> consumer(BlockingQueue<T> queue, int count) {
        return Observable.<T>create(subscriber -> {
            for (int i = 0; i < count; i++) {
                try {
                    T text = queue.take();
                    subscriber.onNext(text);
                }
                catch (InterruptedException ex) {
                    subscriber.onError(ex);
                }
            }
            subscriber.onCompleted();
        }).observeOn(Schedulers.immediate());
    }
}

And I get:

Received One: RxComputationThreadPool-1 at main
Received Two: RxComputationThreadPool-2 at main
Received Three: RxComputationThreadPool-3 at main

So, this works like a charm, but I have the feeling it is still too verbose and that maybe there is a way to make it simpler with RxJava somehow.


texts: Compare ZIP codes, disregarding leading zeros

texts:
I have a function that compares ZIP codes. It also has to handle cases where the input ZIP code be missing leading zeros, have extraneous leading zeros. This is what I've come up with. I don't have any issues with it. But since it's in Scala, I feel there must be a more functional way to write this.

My only functional thought (outside of the digit validation) is to insert them into a collection, then filter the collection by length != 5, and then attempt to fix them.

Here's my imperative, stateful version.

  def compareZip(first: String, second: String): Boolean = {
    var firstTmp: String = null
    var secondTmp: String = null
    if(!first.forall(_.isDigit) || !second.forall(_.isDigit)) false
    else if (first.length == ZIPCODE_LENGTH && first.length == second.length) {
      first equals second
    }
    else {
      if (first.length > ZIPCODE_LENGTH) {
        firstTmp = first takeRight ZIPCODE_LENGTH
      }
      else if (first.length < ZIPCODE_LENGTH) {
        firstTmp = ZERO_STR * (ZIPCODE_LENGTH - first.length) + first
      }
      else firstTmp = first

      if (second.length > ZIPCODE_LENGTH) {
        secondTmp = second takeRight ZIPCODE_LENGTH
      }
      else if (second.length < ZIPCODE_LENGTH) {
        secondTmp = ZERO_STR * (ZIPCODE_LENGTH - second.length) + second
      }
      else secondTmp = second
      firstTmp equals secondTmp
    }
  }


texts: Recursively generate combinations while using Boost Coroutines

texts:
I've tried out implementing a combination generator using boost coroutines. It accepts an array of possible values and generates one array at a time for each combination. As a limitation, it only generates combinations of the same length as the array of possible values and does not check for duplicates inside the source array.

#include <boost/coroutine/coroutine.hpp>
#include <algorithm>
#include <iostream>

template<typename ItElements, typename ItArray, typename Fn>
void enumerate_combinations(ItElements elements_from, ItElements elements_to, ItArray array_from, ItArray array_to,
    Fn&& callback)
{
    for (auto it = elements_from; it != elements_to; ++it)
    {
        *array_from = *it;
        if (std::distance(array_from, array_to) > 1)
        {
            enumerate_combinations(elements_from, elements_to, array_from + 1, array_to, callback);
        }
        else
        {
            callback();
        }
    }
}

template<typename T, size_t nr_elements>
auto enumerate_combinations(T(&elements)[nr_elements])
{
    return boost::coroutines::asymmetric_coroutine<T(&)[nr_elements]>::pull_type(
        [&](boost::coroutines::asymmetric_coroutine<T(&)[nr_elements]>::push_type& sink)
    {
        T buffer[nr_elements];
        std::fill(std::begin(buffer), std::end(buffer), elements[0]);

        enumerate_combinations(std::begin(elements), std::end(elements), std::begin(buffer), std::end(buffer),
            [&]() {sink(buffer);});
    });
}

template<typename T, size_t nr_elements>
std::ostream& print_array(T(&array)[nr_elements], std::ostream& stream, const char* separator = " ")
{
    for (size_t i = 0; i < nr_elements - 1; i++)
    {
        stream << array[i];
        if (separator)
        {
            stream << separator;
        }
    }
    stream << array[nr_elements - 1];
    return stream;
}

int main()
{
    int digits[] = { 1, 2, 3 };
    for (auto& combination : enumerate_combinations(digits))
    {
        print_array(combination, std::cout) << '\n';
    }
}

Any thoughts or reviews?

Running the above code produces:

1 1 1
1 1 2
1 1 3
1 2 1
1 2 2
1 2 3
1 3 1
1 3 2
1 3 3
2 1 1
2 1 2
2 1 3
2 2 1
2 2 2
2 2 3
2 3 1
2 3 2
2 3 3
3 1 1
3 1 2
3 1 3
3 2 1
3 2 2
3 2 3
3 3 1
3 3 2
3 3 3


texts: Optimize platform independent GetTickCount()

texts:
I used this method as a platform independent tick counter. Unfortunately, it consumes ~10 % cpu time in one of my methods. Is there a faster way to solve the issue?

inline uint32_t GetTickCount() {
    using namespace std::chrono;
    return duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
}


texts: Optimization on List key comparisons and return value with HashMap

texts:
Consider this code:

           public class DataSt {

            DataType time;
            DataType memory;

            public DataSt(DataType time, DataType memory)
            {
                this.time=time;
                this.memory=memory;
            }

            private static void saveIt(DataSt p, DataSt p2, String keyval, List<DataSt> comp) {
                  ...
                }

            private static void saveIt( String keyval, List<DataSt> comp) {
                     ...
         }

            public static List<DataSt> compO(List<DataSt> curR, List<DataSt> prevR) {
                Map<String,DataSt> cur = new HashMap<>();Map<String,DataSt> prev= new HashMap<>();
                for(DataSt abc:curR)
                {
                    DataSt v = new DataSt (abc.time,abc.memory);
                    cur.put(abc.key,v);
                }

                for(DataSt abc:prevR)
                {
                    DataSt values = new DataSt (abc.time,abc.memory);
                    prev.put(abc.key,v);
                }

                List<DataSt> comp = new ArrayList<DataSt>();

                for (Entry < String, DataSt > abc: cur.entrySet()) {
                    if (prev.containsKey(abc.getKey())) {
                        saveIt(abc.getValue(), prev.get(abc.getKey()), abc.getKey(), comp);
                    } else {
                        saveIt(abc.getKey(), comp);
                    }
                }

                for (Entry<String, DataSt> abc: prev.entrySet()) {
                    if (!(cur.containsKey(abc.getKey()))) {
                        saveIt(abc.getKey(), comp);
                    }
                }
                return comp;
            }
        }

With reference to the link "https://stackoverflow.com/questions/45230104/list-key-comparisons-and-return-value". It would be great if someone could review the code and suggest optimizations.


texts:
I'm trying to optimize this twiddle computing function:

void twiddle(int N)
{
  int i;
  for (i=0;i<N;i++)
  {
     twiddle_table[i].re = (float)   cos((float)i * 2.0 * PI /(float)N);
     twiddle_table[i].im = (float) - sin((float)i * 2.0 * PI /(float)N);
  }
}

where N = 4096 size of twiddle table and could be bigger!

And then, I did the following:

void twiddle(int N)
{
   int i;
   float Tconst;
   Tconst = 2.0 * PI /(float)N;
   for (i=0;i<N;i++)
   {
      twiddle_table[i].re = (float)   cos((float)i * Tconst);
      twiddle_table[i].im = (float) - sin((float)i * Tconst);
   }
}

But, I'm getting a performance of 340,000 cycles for the for loop, which I think is bad.

Any hints that could enhance the performance of this function?


texts: TemplateString class for re-usable template literals

texts:
I did a little preliminary research and was unable to find a class to create re-usable instances of template string literals, so I wrote my own. Below is the main file (slightly modified to remove exports) written in ES2016, along with a few examples of usage that show the convenience of the class.

const weak = new WeakMap()

function isString (string) {
  return typeof string === 'string'
}

function validateStrings (strings, name = 'strings') {
  if (!Array.isArray(strings) || !strings.every(isString)) {
    throw new TypeError(`${name} must be an array of strings`)
  }
}

function validateValues (values, length) {
  if (!Array.isArray(values) || values.length !== length) {
    throw new TypeError(`values must be an array of length ${length}`)
  }
}

function validateArguments (strings, values) {
  validateStrings(strings)
  validateStrings(strings.raw, 'strings.raw')
  validateValues(values, strings.length - 1)
}

// export
class TemplateString {
  constructor(strings, ...values) {
    validateArguments(strings, values)
    weak.set(this, { strings, values })
  }

  get cooked () {
    const { strings } = weak.get(this)

    return Object.defineProperty(strings.slice(), 'raw', {
      value: strings.raw.slice()
    })
  }

  get raw () {
    return weak.get(this).strings.raw.slice()
  }

  get values () {
    return weak.get(this).values.slice()
  }

  set values (values) {
    const scope = weak.get(this)

    validateValues(values, scope.values.length)

    return scope.values = values
  }

  * [Symbol.iterator] () {
    const { cooked, values } = this

    yield cooked
    yield * values
  }

  toJSON () {
    return this.toString()
  }

  toString () {
    const { strings: cooked, values } = weak.get(this)
    const { length } = values

    const buffer = [cooked[0]]

    for (let index = 0; index < length; index++) {
      buffer.push(String(values[index]))
      buffer.push(cooked[index + 1])
    }

    return buffer.join('')
  }
}

// export default
function templateStringTag (strings, ...values) {
  return new TemplateString(strings, ...values)
}

// example usage
let templateGreeting = templateStringTag`Hello.\nMy name is ${'Inigo Montoya'}.\n\nYou ${'killed my father'}.\nPrepare to ${'die'}.`

// toString() method returns instance as string
console.log(templateGreeting.toString())

// iterator properly spreads instance into arguments of tag function
console.log(String.raw(...templateGreeting))

// all getters intentionally create shallow copies of internal variables
// to prevent accidentally overwriting arrays
let { values } = templateGreeting

values[1] = 'are a potato'
values[2] = 'fry'

// updates values passed into template string
templateGreeting.values = values

// toJSON() method also returns instance as string
console.log(JSON.stringify(templateGreeting))


texts: Configuring a date picker with support for disabled dates

texts:
I'd like to see if I can somehow make this loop more effective (smaller?). I'm using MultiDatesPicker to make a reservation plugin. And I've set everything right, and everything works, but I'd like to see if my jquery code can be optimized somehow.

HTML looks like this (minus the actual calendar):

    Reservation Date:
    <input type="hidden" id="disabled_dates" value=""27.11.2015, 28.11.2015"">
    <input type="text" name="reservation_date" id="reservation_dates_input" value="14.11.2015, 15.11.2015, 25.11.2015">

I have inputs where I have dates that have been reserved #disabled_dates, and in my #reservation_date is the date of the current reservation. Now this input, if you're creating a new reservation, is empty, which means if I don't make the check if it's empty, I'll get an error in my date picker plugin (if the option for it is included). There are double quotes in the #disabled_dates because that's how I get my output from php but the code below deals with that, so that's not an issue at all.

I'm just wondering if this big if - else if - else chunk can be reduced somehow.

jQuery(document).ready(function($) {
    "use strict";

    var disabled_dates = $('#disabled_dates').val(),
        reservation_dates_input = $('#reservation_dates_input').val(),
        disabled_dates_array,
        reserved_dates_array,
        options;

    if (disabled_dates.length) {
        var clean_disabled_dates = disabled_dates.replace(/\"/g, '');
            disabled_dates_array = clean_disabled_dates.split(", ");
    }

    if (reservation_dates_input.length) {
        var clean_reserved_dates = reservation_dates_input.replace(/\"/g, '');
            reserved_dates_array = clean_reserved_dates.split(", ");
    }

    if (disabled_dates.length>2 && reservation_dates_input.length>2) {
        options = {
            firstDay: 1,
            dateFormat: "dd.mm.yy",
            altField: '#reservation_dates_input',
            addDisabledDates: disabled_dates_array,
            addDates: reserved_dates_array
        };
    } else if(disabled_dates.length>2 && reservation_dates_input.length<=2) {
        options = {
            firstDay: 1,
            dateFormat: "dd.mm.yy",
            altField: '#reservation_dates_input',
            addDisabledDates: disabled_dates_array,
        };
    } else if(reservation_dates_input.length>2 && disabled_dates.length<=2) {
        options = {
            firstDay: 1,
            dateFormat: "dd.mm.yy",
            altField: '#reservation_dates_input',
            addDates: reserved_dates_array
        };
    } else {
        options = {
            firstDay: 1,
            dateFormat: "dd.mm.yy",
            altField: '#reservation_dates_input',
        };
    }

    $('#reservation').multiDatesPicker(options);

});

I tried putting empty arrays in the disabled_dates_array and reserved_dates_array, but MultiDatesPicker doesn't allow empty arrays, or arrays with no date in it.


texts: Pretty print with unit and physical suffix II

texts:
Follow up of Pretty print with unit and physical suffix

My first code didn't process negative numbers correctly. Additionally I tried to use all of the helpful input to come up with this solution.

I considered:

precision
testing
spacing tips

P.S.: I use the 'u' instead of U+03BC because I had some difficulties displaying it on my Windows console.

# -*- coding: utf-8 -*-

import math

def eng_format(x, unit='', precision=3):
    UNITS = [' ', ' k', ' M', ' G'] + \
            ([None] * 10) + \
            [' f', ' p', ' n', ' u', ' m']

    power_of_1000 = int(math.floor(math.log10(abs(x)) // 3))
    exponent = 3 * power_of_1000
    prefix = UNITS[power_of_1000]
    if prefix is None:
        prefix = '*10^%d ' % exponent

    predecimal = 1+int(math.floor(math.log10(abs(x)) % 3))
    significand = x * 10**(-exponent + precision - predecimal)
    significand = round(significand) / 10**(precision - predecimal)

    postdecimal = precision - predecimal
    if(postdecimal < 0):
        postdecimal = 0
    FormatStr = '{:.%df}{:s}{:s}'%(postdecimal)
    return FormatStr.format(significand, prefix, unit)

if __name__ == '__main__':
    import unittest

    class TestPrettyPrinting(unittest.TestCase):
        def setUp(self):
            self.seq = list()
            self.seq.append( (0.002777, 'V', 3, '2.78 mV') )
            self.seq.append( (0.02777, 'V', 3, '27.8 mV') )
            self.seq.append( (0.2777, 'V', 3, '278 mV') )
            self.seq.append( (2.777, 'V', 3, '2.78 V') )
            self.seq.append( (27.77, 'V', 3, '27.8 V') )
            self.seq.append( (2./3, 'V', 6, '666.667 mV') )
            self.seq.append( (0.000003221, 'A', 3, '3.22 uA') )
            self.seq.append( (30589, 'A', 4, '30.59 kA') )
            self.seq.append( (60000000, 'W', 6, '60.0000 MW') )
            self.seq.append( (6000000000000000, 'W', 1, '6*10^15 W') )
            self.seq.append( (.0000000000000006, 'W', 4, '600.0*10^-18 W') )

        def test_eng_format(self):
            for value, unit, precission, expected_result in self.seq:
                for si, s in enumerate(['', '-']):
                    new_expected_result = s + expected_result
                    result = eng_format(value * (-1)**si, unit, precission)
                    print "%20s %20s"%(result, new_expected_result)
                    self.assertEqual(result, new_expected_result)

    unittest.main()


texts: "Partial solution" on Code Eval for Clojure FizzBuzz

texts:
I'm just getting started on the site CodeEval, and I submitted my first solution today. What I don't understand is why it's marking my (working) answer as only a "partial solution". The site doesn't seem to want to explain why my answer is only "partial", and I'm hoping someone here can explain why.

The challenge I was trying to do was FizzBuzz, where you take in three numbers as input and output a sequence of increasing numbers, substituting "F" for a number if it's divisible by the first input number, "B" for a number if it's divisible by the second input number, and "FB" if it's divisible by both.

Here's my solution:

(defn process-line [[x y n]]
  (for [i (range 1 (inc n))]
(cond

  (and (zero? (mod i x)) (zero? (mod i y))) "FB"
  (zero? (mod i x)) "F"
  (zero? (mod i y)) "B"

  :else (str i))))

(defn string->int [string]
  (let [elements (clojure.string/split string #" ")]
    (into [] (map read-string elements))))

; Sample code to read in test cases:
; Open the file passed as the first command line argument
(with-open [rdr (clojure.java.io/reader (first *command-line-args*))]
  ; Read each line ignoring empty ones
  (doseq [line (remove empty? (line-seq rdr))]
    (let [out-line (process-line (string->int  line))]
    (println (clojure.string/join " " out-line)))))

The only thing I can think of is the following: when it shows the memory usage of my working solution (it currently uses 71098368 bytes) there's a little tooltip that says "Reduce memory usage to 20Mb". Is that the cause of the "partial" in my solution, and, if so, how could I reduce my memory usage? My solution already seems pretty simple.


texts:
I'm still a beginner, so I'm still learning. I'm trying to take test scores for 3 different students, enter them in an array, then display the name, test scores and the average. Trying to also have reusable code for the average. I'm not even sure I'm going about it the right way. This is what I've got so far. It works, but its probably sloppy. I'm sure there are other ways of doing it, but some constructive criticism would be nice.

static void Main(string[] args)
    {
        const int STUDENTS = 3;
        string[] names = new string[STUDENTS];
        names[0] = "Morgan";
        names[1] = "Bowie";
        names[2] = "Ananya";

        Console.WriteLine("Enter test scores for " + names[0]);
        const int MORGAN_TEST = 3;
        int[] morganScores = new int[MORGAN_TEST];

        morganScores[0] = int.Parse(Console.ReadLine());
        morganScores[1] = int.Parse(Console.ReadLine());
        morganScores[2] = int.Parse(Console.ReadLine());
        int sumMorgan = morganScores.Sum();

        Console.WriteLine("Enter test scores for " + names[1]);
        const int BOWIE_TEST = 5;
        int[] bowieScores = new int[BOWIE_TEST];

        bowieScores[0] = int.Parse(Console.ReadLine());
        bowieScores[1] = int.Parse(Console.ReadLine());
        bowieScores[2] = int.Parse(Console.ReadLine());
        bowieScores[3] = int.Parse(Console.ReadLine());
        bowieScores[4] = int.Parse(Console.ReadLine());
        int sumBowie = bowieScores.Sum();

        Console.WriteLine("Enter test scores for " + names[2]);
        const int ANANYA_TEST = 4;
        int[] ananyaScores = new int[ANANYA_TEST];

        ananyaScores[0] = int.Parse(Console.ReadLine());
        ananyaScores[1] = int.Parse(Console.ReadLine());
        ananyaScores[2] = int.Parse(Console.ReadLine());
        ananyaScores[3] = int.Parse(Console.ReadLine());
        int sumAnanya = ananyaScores.Sum();

        double[] average = { MORGAN_TEST, BOWIE_TEST, ANANYA_TEST };

        Console.WriteLine(names[0] + " " + morganScores[0] + " " + morganScores[1] + " " + morganScores[2] + " Average score: {0:N2}", sumMorgan / average[0]);
        Console.WriteLine(names[1] + " " + bowieScores[0] + " " + bowieScores[1] + " " + bowieScores[2] + " " + bowieScores[3] + " " + bowieScores[4] + " Average score: {0:N2}", sumBowie / average[1]);
        Console.WriteLine(names[2] + " " + ananyaScores[0] + " " + ananyaScores[1] + " " + ananyaScores[2] + " " + ananyaScores[3] + " " + " Average score: {0:N2}", sumAnanya / average[2]);
        Console.Read();
    }


texts: Search through fortran source for a string ignoring comments

texts:
I am trying to write a python script that can search through Fortran code
ignoring comments. I didn't find a simple way of doing this using grep. So I startwed writing my own.
The rules for comments that I am following are:

the first character is not a space or a number. It is usually a c, C but I've seen * and other variations
the above condition can be violated if its a fortran90/95 code in that case, its complicated so I am not treating that case for now.
the first non-space character is a "!"

I could not find a simple solution that ignores all types of fortran comments in text so I started writing my own in python 2.x. It looks dirty but works in many cases.
#!/usr/bin/python
import sys
def fgrep(file_name, cond):
      first_valid_chars=tuple(range(0,10 )) + (' ',)
      with open(file_name, 'r') as f:
          for line in f:
            if line[0] in first_valid_chars:
                line1 = line.strip()
                if line1:    # ignore empty lines
                     if line1[0] != '!':
                         # fortran is case insensitive so comparing lower to lower
                         if cond.lower() in line1.lower():
                               print(line1)

if __name__ == "__main__":
   print(sys.argv[1])
   file_name = sys.argv[1]
   cond = sys.argv[2]

   fgrep(file_name, cond)

It's drty, not clean and too many indents. How do I clean this up? Because I copy-pasted from editor, there could be errors due to indentation.


texts:
I am having a look at Rust, this is the first data structure I have tried to implement ( the standard library has a max-heap implementation, so this is a learning exercise ).
/// Heap is an array organised so the smallest element can be efficiently removed.
pub struct Heap<T>{ vec: Vec<T> }

impl<T: Ord+Copy> Heap<T> // Ord+Copy means T can be compared and copied.
{
  /* Diagram showing numbering of tree elements.
           0
       1       2
     3   4   5   6

     The fundamental invariant is that a parent element is not greater than either child.
     H[N] <= H[N*2+1] and H[N] <= H[N*2+2]
  */

  /// Create a new heap.
  pub fn new( capacity : usize ) -> Heap<T>
  {
    Heap{ vec: Vec::with_capacity( capacity ) }
  }

  /// Get the number of elements in the heap.
  pub fn count( &mut self ) -> usize
  {
    self.vec.len()
  }

  // add and make allow the heap to be efficiently initialised.

  /// Add an element to the array ( not yet a heap ).
  pub fn add( &mut self, x: T )
  {
    self.vec.push( x );
  }

  /// Make the array into a heap.
  pub fn make( &mut self )
  {
    // Initialise the heap by making every parent not greater than both it's children.

    let count = self.vec.len();
    let mut parent = count / 2;
    while parent > 0
    {
      parent -= 1;
      let mut check = parent;
      // Move element at check down while it is greater than a child element.
      let elem : T = self.vec[ check ];
      loop
      {
        let mut child = check * 2 + 1;
        if child >= count { break }
        let mut ce: T = self.vec[ child ];
        if child + 1 < count
        {
          let ce2: T = self.vec[ child + 1 ];
          if ce2 < ce { child += 1; ce = ce2; }
        }
        if ce >= elem { break }
        self.vec[ check ] = ce;
        check = child;
      }
      self.vec[ check ] = elem;
    }
  }

  /// Insert a new element into the heap.
  pub fn insert( &mut self, elem: T )
  {
    let mut child = self.vec.len();
    self.vec.push( elem );
    // Move the new element up the tree until it is not less than it's parent.
    while child > 0
    {
      let parent = ( child - 1 ) >> 1;
      let pe: T = self.vec[ parent ];
      if elem >= pe { break }
      self.vec[ child ] = pe;
      child = parent;
    }
    self.vec[ child ] = elem;
  }

  /// Remove and return the smallest element.
  pub fn remove ( &mut self ) -> T
  {
    // The result is element 0.
    // The last element in the heap is moved to 0, then moved down until it is not greater than a child.
    let result = self.vec[ 0 ];
    let last = self.vec.len() - 1;
    let elem = self.vec[ last ];
    self.vec.pop();
    if last > 0
    {
      let mut parent = 0;
      loop
      {
        let mut child = parent * 2 + 1;
        if child >= last { break }
        let mut ce = self.vec[ child ];
        if child + 1 < last
        {
          let ce2 = self.vec[ child + 1 ];
          if ce2 < ce
          {
            child += 1;
            ce = ce2;
          }
        }
        if ce >= elem { break }
        self.vec[ parent ] = ce;
        parent = child;
      }
      self.vec[ parent ] = elem;
    }
    result
  }
} // end impl Heap


texts:
Beginner level script for a countdown timer. Would appreciate if you could point the things I could do to be more efficient.
Basically, I would want to check if the current day is either a "workday"(Mon - Wed) or a "freeday"(Thur-Sun) and achieve the following:

If it's a workday, and the current hour is a working hour (7:00:00 AM - 5:00:00 PM), then count
how many hour(s) remaining till end of the shift (5PM) base on the current time.

If it's a workday, and the current hour is outside of working hours (5:00:01 PM to 6:59:59 AM), say that it is not yet a working hour.

If it's a freeday, count till the next Monday.

I wouldn't want to rely on the if statements if possible, but my understanding level for Python is at this point only. Is there a better way to do it?
Thank you in advance! Happy coding.
import time, datetime

# Add the value to get the next Monday
get_future_monday = {
    0: 1,
    1: 2,
    2: 3,
    3: 4
}

def time_state():
    # Check what day of the week
    # 0 == Monday, 6 == Sunday
    check_day = datetime.datetime.today().weekday()

    # Get future Monday
    future_monday = 6 - check_day

    # Check current time
    check_time_now = datetime.datetime.now()

    # Parse current time
    # Get the year, month and day
    get_year = check_time_now.year
    get_month = check_time_now.month
    get_day = check_time_now.day

    # Define timespan for each routine
    working_hours = datetime.time(7, 0, 0)
    after_hours_am = datetime.time(6, 59, 59)
    after_hours_pm = datetime.time(17, 0, 1)

    if check_day == 0 and check_time_now.time() < after_hours_am: # If Monday and current time not yet 7 AM
        print("It's not time yeeeet!")
        return datetime.datetime(get_year, get_month, get_day, 7, 0, 0)

    elif check_day == 2 and check_time_now.time() > after_hours_pm: # If Wednesday and current time past 5 PM
        print("Time to gooooo!")
        return datetime.datetime(get_year, get_month, (get_day + get_future_monday[future_monday]), 7, 0, 0)

    elif check_day <= 2 and check_time_now.time() < after_hours_am: # If day in Tuesday, Wed and current time not yet 7 AM
        print("Get ready to grind...")
        return datetime.datetime(get_year, get_month, get_day, 7, 0, 0)

    elif check_day <= 2 and check_time_now.time() > after_hours_pm: # If day in Tuesday, Wed and current time not yet 5 PM
        print("Free at last!")
        return datetime.datetime(get_year, get_month, (get_day + 1), 7, 0, 0)

    elif check_day <= 2 and check_time_now.time() >= working_hours and check_time_now.time() <= after_hours_pm: # If day in Mon - Wed and current time not yet 5 PM
        print("Focus focus focus!!!")
        return datetime.datetime(get_year, get_month, get_day, 17, 0, 0)

    else:
        print("Playtime foo UwU")
        return datetime.datetime(get_year, get_month, (get_day + get_future_monday[future_monday]), 7, 0, 0) # Playtime

def countdown(time_state):
    time_state = time_state

    clock_tick = time_state - datetime.datetime.now()

    days = clock_tick.total_seconds() / 86400
    hours, rem = divmod(clock_tick.total_seconds(), 3600)
    mins, secs = divmod(rem, 60)

    print(f"{int(days):02d}:{int(hours):02d}:{int(mins):02d}:{int(secs):02d}")
    time.sleep(1)

def main():
    while True:
        a = time_state()
        countdown(a)

main()
```


texts:
I have wrote a simple util to submit my code to a online judge site, how to avoid the evil function?

(setq url-proxy-services '(("http" . "localhost:8888")))
(setq debug-on-error t)

(require-package 'http-post-simple)
(require 'http-post-simple)
(eval-when-compile (require 'cl))

(defstruct form action (method "POST") fields)

(defstruct site url forms)

(setq poj (make-site :url "http://poj.org" :forms '(
                            (login .
                               (make-form
                                :action "login"
                                :fields `(
                                      (user_id1 . "you-name")
                                      (password1 . ,(read-passwd "input your password: "))
                                      (url . "%2F")
                                      (B1 . "login"))))
                            (submit .
                                (make-form
                                 :action "submit"
                                 :fields `(
                                       (problem_id ,(read-string "inpur problem id: "))
                                       (language ,(read-string "select language: 0:G++,1:GCC,2:Java,3:Pascal,4:C++,5:C,6:Fortan "))
                                       (source ,(with-temp-buffer
                                          (insert-file-contents (read-file-name "select source file"))(buffer-string)))
                                       (submit "Submit"))))
                            (logout .
                                (make-form
                                 :action "login?action=logout&url=%2F"
                                 :method "GET")))))

(defun http-get-simple(url)
          (let (header data status)
            (with-current-buffer
            (url-retrieve-synchronously url)
              (setq status url-http-response-status)
              (goto-char (point-min))
              (if (search-forward-regexp "^$" nil t)
              (setq header (buffer-substring (point-min) (point))
                data   (buffer-substring (1+ (point)) (point-max)))
            (setq data (buffer-string)))
              (kill-buffer (current-buffer)))
              (values data header status)))

(defun request-site(site form)
  "perform a request to site"
  (let* ((url (site-url site))
     (form (cdr (assoc form (site-forms site))))
     (form-inst (eval form))
     (result (if (equal (form-method form-inst) "POST")
             (http-post-simple (concat url "/" (form-action form-inst))
                       (form-fields form-inst))
           (http-get-simple (concat url "/" (form-action form-inst))))))
    result))

(defun poj-login()
  (interactive)
  (request-site poj 'login))

(defun poj-logout()
  (interactive)
  (request-site poj 'logout))

(defun poj-submit()
  (interactive)
  (request-site poj 'submit))

Above is my code, I have tried this

(let* ((form (cdr (assoc 'submit (site-forms poj))))
       (frm-inst (apply (car form) (cdr form)))) ; get weird result
  (eval form)) ; get proper result

And can you give me some advice about coding style?


texts: Remove items, resize columns, shuffle a list

texts:
I'm at the very beginning of starting to learn object-oriented programming patterns in JavaScript and PHP.  Up until now I've always coded in a purely functional pattern.  I'm doing a lot of reading, but I think what would really help me is being able to see a direct correlation between how my code is currently written and how it would be written in OO.

Could someone explain to me how I could write something like this, which consists of several event functions, in an object-oriented fashion?

(function ( $, window, document, undefined ) {
setTimeout(function(){
    $(document.body).append('

');
    $(document.getElementById('instruction')).animate({'opacity':1},1500);
},400);

$( document ).on( 'click', '*', function () {
    $(document.getElementById('instruction')).animate({'opacity':0},1500,function(){
        $(this).remove();
    });
});

var l = document.getElementById('left');
var r = document.getElementById('right');

// Expand right section
$('hr').on('click', function(){
    $('article').show().removeClass('short').animate({'opacity':1}, function(){
        $(this).find('p').show();
        var m = $(document.getElementById('middle'));
        var h = Math.max(l.offsetHeight,r.offsetHeight);
        m.css({'height':h + 'px'});
    });
});

$('#step2').on('click', function(){
    $(this).remove();
    $('<button id="shuffle">SHUFFLE</button>').appendTo('footer');
});

// remove list items
$( document ).on( 'click', 'span', function () {
    var subtract = $(this).parent().height();
    $(this).parent().remove();
    var m = $(document.getElementById('middle'));

    var h = Math.max(l.offsetHeight,r.offsetHeight);
    m.css({'height':h + 'px'});
})

// shuffle
$( document ).on( 'click', '#shuffle', function () {
    var ul = document.querySelector('ul');
    for (var i = ul.children.length; i >= 0; i--) {
        ul.appendChild(ul.children[Math.random() * i | 0]);
    }
});
var load = false;
$(window).resize(function(){
    var m = $(document.getElementById('middle'));
    if (load == false) { // only need to do this once
        $.getJSON('',
            function(e) { // load data from Google Spreadsheet
                var t = 1,a,l;
                for (var n = 0; n < e.feed.entry.length; n++) {
                    a = e.feed.entry[n].gsx$name.$t;
                    l = '
' + a + 'remove
';
                    $("ul").prepend(l);
                }
                t++
            }
        )
        .success(function(){ // evaluate height, set vertical rule
            var h = Math.max(l.offsetHeight,r.offsetHeight);
            m.css({'height':h + 'px'});
        })
        .fail(function() { // load something even if there is no connection
            var s = ['Lorem','ipsum'];
            var a = s.length;
            for (var i = 0; i < a; i++) {
                l = '
' + s[i] + '
';
                $("ul").prepend(l);
            }
        });

        $.getJSON('',
            function(e) {
                var t = 1,a,l;
                for (var n = 0; n < e.feed.entry.length; n++) {
                    a = e.feed.entry[n].gsx$paragraph.$t;
                    l = '
' + a + '
';
                    $("article").prepend(l);
                }
                t++
            }
        )
    }
    var h = Math.max(l.offsetHeight,r.offsetHeight);
    m.css({'height':h + 'px'});

    load = true;
}).resize();

})( jQuery, window, document );

The code block is not really relevant beyond serving as an example for me, but its purpose is merely a test, visible here.  It consists of a 2-column layout with a border between the two. The middle border must always equal the tallest column and each columns height needed to be manipulable, with a secondary step to shuffle the order of the content on the left side.


texts: Strategy pattern for four arithmetic operations

texts:
I am studying design patterns, I was wondering if my approach makes sense.
I am trying to implement the strategy pattern. I think I have captured the essence which is

Define a family of algorithms,
encapsulate each one,
and make them interchangeable,

as shown in the example code below.

Have I captured the intent, am I missing something from the example?

#include "stdafx.h"
#include <iostream>

#include <iostream>
#include <fstream>
#include <string>

enum OperationType
{
    Add = 1, Subtract, Multiply, Divide
};

class Operation
{
public:
    Operation(int Value1, int Value2) :
        m_Value1(Value1),
        m_Value2(Value2) {      }

    virtual int Calculate() = 0;

private:

    int m_Result;
    int m_Value1;
    int m_Value2;

};

class Addition : public Operation
{
public:
    Addition(int Value1, int Value2) : Operation(Value1,Value2),
        m_Value1(Value1), m_Value2(Value2) {}

    int Calculate()
    {
        m_Result = m_Value1 + m_Value2;
        return m_Result;
    }

private:

    int m_Result;
    int m_Value1;
    int m_Value2;

};

class Subtraction : public Operation
{
public:
    Subtraction(int Value1, int Value2) : Operation(Value1, Value2),
        m_Value1(Value1), m_Value2(Value2) {}

    int Calculate()
    {
        m_Result = m_Value1 - m_Value2;
        return m_Result;
    }

private:

    int m_Result;
    int m_Value1;
    int m_Value2;

};

class Multiplication : public Operation
{
public:
    Multiplication(int Value1, int Value2) : Operation(Value1, Value2),
        m_Value1(Value1), m_Value2(Value2) {}

    int Calculate()
    {
        m_Result = m_Value1 * m_Value2;
        return m_Result;
    }

private:

    int m_Result;
    int m_Value1;
    int m_Value2;

};

class Division : public Operation
{
public:
    Division(int Value1, int Value2) : Operation(Value1, Value2),
        m_Value1(Value1), m_Value2(Value2) {}

    int Calculate()
    {
        m_Result = m_Value1 / m_Value2;
        return m_Result;
    }

private:

    int m_Result;
    int m_Value1;
    int m_Value2;

};

class Test
{
    public:

        Test()
        {
            m_Operation = NULL;
        }

        void SetOperation(int Value1, int Value2, int Operation)
        {
            switch (Operation)
            {
                case Add:
                {
                    m_Operation = new Addition(Value1, Value2);
                }
                break;

                case Subtract:
                {
                    m_Operation = new Subtraction(Value1, Value2);
                }
                break;

                case Multiply:
                {
                    m_Operation = new Multiplication(Value1, Value2);
                }
                break;

                case Divide:
                {
                    m_Operation = new Division(Value1, Value2);
                }
                break;
            }
        }

        int PerformOperation()
        {
            return m_Operation->Calculate();
        }

private:
    Operation *m_Operation;

};

int main()
{
    Test test;

    test.SetOperation(1, 2, OperationType::Add);
    std::cout << test.PerformOperation() << std::endl;

    test.SetOperation(2, 3, OperationType::Subtract);
    std::cout << test.PerformOperation() << std::endl;

    test.SetOperation(3, 4, OperationType::Multiply);
    std::cout << test.PerformOperation() << std::endl;

    test.SetOperation(40, 10, OperationType::Divide);
    std::cout << test.PerformOperation() << std::endl;

    int x;
    std::cin >> x;
    return 0;
}


texts:
This is the Daily Temperatures problem at leetcode.com:

  Given a list of daily temperatures, produce a list that, for each day
  in the input, tells you how many days you would have to wait until a
  warmer temperature. If there is no future day for which this is
  possible, put 0 instead.

  For example, given the list temperatures = [73, 74, 75, 71, 69, 72,
  76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].

  Note: The length of temperatures will be in the range [1, 30000]. Each
  temperature will be an integer in the range [30, 100].

This code works for smaller inputs and fails for list of length 10,000. What would you recommend me to change or improve in this code?

class Solution(object):
    def dailyTemperatures(self, temperatures):
        """
        :type temperatures: List[int]
        :rtype: List[int]
        """
        #O(n2)
        #max(temperatures)
        res=[]
        for i in range(len(temperatures)):
            cnt=0
            for j in range(i+1,len(temperatures)):
                cnt+=1
                if temperatures[i]<temperatures[j]:
                    res.append(cnt)
                    cnt=0
                    break
                elif j==len(temperatures)-1:
                    res.append(0)
                    cnt=0
                    break
        res.append(0)
        return res


texts:
Let L be the language defined as follows:

The words are made up of strings of a’s followed by b’s.
The number of a’s is always equal to the number of b’s.
Examples of words that belong to L are: ab, aabb, aaabbb etc...

One way to test if a word w belong to this language is to use a stack to check if the number of a’s balances the number of b’s.

This is what I though of doing:

Check if the length string is even
If it is send input to the function
Divide length by two and push the a's onto a stack
Reverse the string
Divide length by two and push the b's onto a stack
While the stack isn't empty pop each and store the count of each
Compare the count and if they are equal then return 0 or if not return 1

Please see below for the program I implemented:
#include <iostream>
#include <string>
#include <stack>
#include <algorithm>

using namespace std;

int count1 = 0;
int count2 = 0;

bool isInLanguageL (string w);

int main()

{
    string input;

    cout << "Input any string; ";
    getline(cin,input);

    if (input.length() % 2 != 0)
        cout <<"Pattern entered does not match the language ";
    else
        isInLanguageL(input);

    return 0;
}

bool isInLanguageL (string w)
{
    stack<string> word1, word2;
    string a, b;

        for (unsigned i = 0; i < w.length()/2; i++)
    {
           a = w.at(i);
           word1.push(a);

    }

    reverse(w.begin(), w.end());

    for (unsigned i = 0; i < w.length()/2; i++)
    {
           b = w.at(i);
           word2.push(b);

    }

while(!word1.empty() && !word2.empty())
{

    word1.pop();
    count1 = count1++;
    word2.pop();
    count2 = count2++;

}

if(count1 == count2)
    return true;
else
    return false;

}

The issue I have with this is despite it working correctly I would appreciate and opinion on it as I feel they may have been another way to approach handling the strings although after racking my brains this was the best solution I could come up with.
What seems a bit silly to me is where I am comparing counts of the two stacks as it's pretty obvious based on the fact that I am not allowing odd numbers to pass into the function that the counts will always be equal which would also be due to the division by 2 in each iteration which clearly rules out the counts ever not being equal.
Also, it's all good and well that I am using the stacks to compare counts but I'm not really doing a check here on whether or not the string matches a pattern. In my mind I would have used the approach of checking a pattern but as the question just wants to see whether a's and b's balance I thought this approach wouldn't be bad.
Any advice on how else to approach this question would be appreciated.
Thanks


texts:
This code is for a simple 2D tile-based game. x1 and y1 are the mouse coordinates in the world. entity->x1 and entity->y1 is the point where the player is, the shot origin.

I would like to know how to keep the current output while simplifying the code and improving performance.

void shoot(Map *map, Entity *entity, int x1, int y1)
{
    float slope = (y1 - entity->y1) / (x1 - entity->x1);
    float y = entity->y1; //Weapon position
    Block *block;

    if(x1 > entity->x1){
        y += slope;
        for(float x = entity->x1 + 1; x < map->width && y < map->height && y > 0; ++x){

            //Get block at position x y. Check if found a hit
            if((block = map_block_at(map, x, y))->type != EMPTY){
                block_cause_damage(block, entity->hand_item->weapon.damage);
                return;
            }

            y += slope;
        }
    }

    else
    if(x1 < entity->x1){
        y -= slope;
        for(float x = entity->x1 - 1; x > 0 && y < map->height && y > 0; --x){

            //Get block at position x y. Check if found a hit
            if((block = map_block_at(map, x, y))->type != EMPTY){
                block_cause_damage(block, entity->hand_item->weapon.damage);
                return;
            }

            y -= slope;
        }
    }

    //When the player shoots up or down
    else {
        slope = (y1 > entity->y1) ? 1 : - 1;
        y += slope;
        while(y < map->height && y > 0){

            //Get block at position x y. Check if found a hit
            if((block = map_block_at(map, x1, y))->type != EMPTY){
                block_cause_damage(block, entity->hand_item->weapon.damage);
                return;
            }

            y += slope;
        }
    }
}

The code for Entity and Map:

typedef struct Entity {
    Renderable renderable;
    plist_id render_id;
    Point (*get_current_position)(struct Entity *, uint32_t);
    int health, attack_damage, running, jumping;
    float x0, y0, x1, y1;
    uint32_t t0, t1;
    enum {LEFT, RIGHT} side;
    Image **texture;
    Item *hand_item;
    Backpack backpack;
} Entity;

typedef struct {
    Renderable renderable;
    plist_id render_id;
    int width, height;
    Block *blocks;
    Camera *camera;
} Map;


texts:
I need to create a method to debias biased bytes from the method get_raw_bytes(length) using von Neumann debiasing method.

Von Neumann method takes two bits at a time. If the input is 01 it will output 0, if the input is 10, it will output 1, if the input is 00 or 11, it won't output anything.

Example:

Raw      : [11010110, 11001001, 01101000]
Debiased : [00110011]

Here's my current code:

def get_raw_bytes(length):
    return open('/dev/hwrng', 'rb').read(length)

def get_debiased_bytes(length):
    arr_debiased_bytes = []
    debiased_byte = 0
    bit_counter = 0
    while len(arr_debiased_bytes) < length:
        raw_bytes = get_raw_bytes(length * 5)
        for byte in raw_bytes:
            for k in range(0, 8, 2):
                bit1 = byte >> k & 1
                bit2 = byte >> k + 1 & 1
                if bit1 != bit2:
                    debiased_byte = debiased_byte << 1 | bit1
                    bit_counter += 1
                    if bit_counter == 8:
                        arr_debiased_bytes.append(debiased_byte)
                        debiased_byte = 0
                        bit_counter = 0
    return bytes(arr_debiased_bytes[:length])

I think my code still can be improved and tidied up. Can anyone help me with this?


texts: Minimum Value evenly divisible by all integers from 1 to n

texts:
I have just started learning python and I am solving Project Euler problems alongside for practice. This is my solution for problem 5. Project Euler asks for the minimum value divisible by all numbers from 1 to 20 but I have made the program so it works from 1 to n.

I think there is a lot of room for improvement in it and I need your suggestions. Please tell me how I can improve it.

def least(x):
    """
    Variables:
    x = Argument of function and the maximum value of range.
    n = Number that is going to be tested by loops in each cycle.
    a = Number that is going to be added to "n" in each cycle of loop. It is initialized with "x".
        For example: if we check for all numbers from 1 to 10, each "n" has to be multiple of 10. So that's why
        a will be added to n in each turn.
    y = To minimize machine time, I have tried to bring argument of "least" function below 10.
        So if x is bigger than 10, y will be x - 10. And then we will do recursion and use "least" on y.

        For example: If we check from 1 to 40.
            least(40) -> n = least(30) = a                          (calls least(30) to get n and a)
                least(30) -> n = least(20) = a                      (calls least(20) to get n and a)
                    least(20) -> n = least(10) = a                  (calls least(10) to get n and a)
                        least(10) -> n = 10, a =10, (Brute Check)
                            (Brute Check)
        (At each stage "for loop" checks "n" in each loop cycle and adds "a" until value found.)
    """
    if x <= 10:
        n = x #The first number to test
        a = x #a is number that's going to be added in each turn
    else:
        y = x - 10
        n = least(y) #Recursion to minimize machine load and time
        a = n
    while True:
        d = 0
        for i in range(1,x + 1):
            if n % i == 0:
                d += 1 #counts if i evenly divides.
            else:
                break #Checks each n. If i doesn't evenly divide, skips loop cycle.
        if d == x: #if each "i" divides evenly, d will be equal to x and thus minimum value will be n.
            return n
        else:
            n += a #adds a(specified above)
minimumvalue = least(int(input("Minimum Value divisible by all integers from 1 to n.\n Specify n: ")))
print(" Minimum Value: " + str(minimumvalue))

Github Link


texts: SQL LIKE search in Angular filter objects

texts:
I made this AngularJS 1.x filter, to search using a the same SQL LIKE syntax. Right now only the percentage symbol (%) is supported, the underscore symbol (_) is not.

Under the hood I'm simply building a RegExp from a format string passed as a parameter (ie. the search string), then I'm looping over all the object properties inside an input array (first parameter).

I'm looking for some feedback about performance, and in particular about any possible "edge cases" in which it would perform bad or could possibly break.

Here's the code (ES6/ES2015 syntax):

"use strict";

export default function likeFilter() {
  return (input, format) => {
    if (!(input instanceof Array && "string" === typeof format && format.length)) {
      return input;
    }

    const like = format.indexOf("%") >= 0;
    const startLike = like && format.charAt(0) === "%";
    const endLike = like && format.charAt(format.length - 1) === "%";
    const split = [];

    split.splice(0, 0, ...format.split("%"));

    if (startLike) {
      split.shift();
    }

    if (endLike) {
      split.pop();
    }

    let regexp = split.join(".*");

    if (!startLike) {
      regexp = "^" + regexp;
    }

    if (!endLike) {
      regexp += "$";
    }

    regexp = new RegExp(regexp, "mi");

    return input.filter(el => {
      for (let key in el) {
        if (el.hasOwnProperty(key)) {
          if (regexp.test(el[key])) {
            return true;
          }
        }
      }

      return false;
    });
  }
};

Example usage:

JS code (angular filters module):

"use strict";
import likeFilter from "./like";
filtersModule.filter("like", likeFilter);

HTML code (angular template):

<input type="text" ng-model="data.searchstring" />


texts:
This script counts how many matches were won by the team with a first half, second half, and full game time of possession differential advantage.

The data is stored in a pandas data frame:

   Points  H1  H2  Total
0      36  46  50     96
1      -5  16  18     34
2      47  12  65     77
3      12  79  13     92
4      -7  53 -64    -11
5      36  -3 -55    -58
6       9  27  87    114
7      17  66 -10     56

The script counts matches won by a team with a positive time of possession differential as well as matches lost by a team with a negative time of possession differential.

From the above example data, matches 0,2,3,4,6,7 would be selected for total wins because the team with the possession advantage won or the team with the possession disadvantage lost.

Match 1 was lost by the team with more total possession. Match 5 was won by the team with less total possession.

This snippet finds the winners for first half, second half, and the total match time.

total_win = ((poss_diff['Points'] > 0) & (poss_diff['Total'] > 0) | (poss_diff['Points'] < 0) & (poss_diff['Total'] < 0))
h1_win = ((poss_diff['Points'] > 0) & (poss_diff['H1'] > 0) | (poss_diff['Points'] < 0) & (poss_diff['H1'] < 0))
h2_win = ((poss_diff['Points'] > 0) & (poss_diff['H2'] > 0) | (poss_diff['Points'] < 0) & (poss_diff['H2'] < 0))
print len(poss_diff[total_win])
print len(poss_diff[h1_win])
print len(poss_diff[h2_win])

Is there a more Pythonic way to calculate and store the results using lambda, applymap, or another function?