texts: Partitioning a list to a list of smaller lists

texts:
I created a utility method ListUtils.partition(iterable, size) to partition a potentially large list to a list of smaller lists:

public class ListUtils {
    public static <T> List<List<T>> partition(Iterable<T> iterable, int size) {
        if (iterable == null) {
            return Collections.emptyList();
        }
        if (size < 1) {
            List<T> list = new ArrayList<>();
            for (T item : iterable) {
                list.add(item);
            }
            return Arrays.asList(list);
        }
        List<List<T>> result = new ArrayList<>();
        List<T> segment = new ArrayList<>(size);
        int i = 0;
        for (T item : iterable) {
            segment.add(item);
            if (++i == size) {
                result.add(segment);
                segment = new ArrayList<>(size);
                i = 0;
            }
        }
        if (i > 0) {
            result.add(segment);
        }
        return result;
    }
}

Unit tests:

public class ListUtilsTest {
    private <T> List<List<T>> partition(Iterable<T> iterable, int size) {
        return ListUtils.partition(iterable, size);
    }

    @Test
    public void testPartitionEmpty() {
        assertEquals(Arrays.<List<Object>>asList(), partition(Arrays.asList(), 3));
    }

    @Test
    public void testPartitionNull() {
        assertEquals(Arrays.<List<Object>>asList(), partition(null, 3));
    }

    @Test
    public void testPartitionZeroSize() {
        List<Integer> orig = Arrays.asList(1, 2, 3);
        assertEquals(Arrays.asList(orig), partition(orig, 0));
    }

    @Test
    public void testPartitionNegativeSize() {
        List<Integer> orig = Arrays.asList(1, 2, 3);
        assertEquals(Arrays.asList(orig), partition(orig, -3));
    }

    @Test
    public void testPartitionInts() {
        assertEquals(
                Arrays.asList(
                        Arrays.asList(1, 2),
                        Arrays.asList(3, 4),
                        Arrays.asList(5)),
                partition(Arrays.asList(1, 2, 3, 4, 5), 2));
    }

    @Test
    public void testPartitionStrings() {
        assertEquals(
                Arrays.asList(
                        Arrays.asList("1", "2"),
                        Arrays.asList("3", "4"),
                        Arrays.asList("5")),
                partition(Arrays.asList("1", "2", "3", "4", "5"), 2));
    }

    @Test
    public void testPartition_MultipleOfSize() {
        assertEquals(
                Arrays.asList(
                        Arrays.asList(1, 2),
                        Arrays.asList(3, 4)),
                partition(Arrays.asList(1, 2, 3, 4), 2));
    }

    @Test
    public void testPartition_Size1() {
        assertEquals(
                Arrays.asList(
                        Arrays.asList(1),
                        Arrays.asList(2),
                        Arrays.asList(3),
                        Arrays.asList(4)),
                partition(Arrays.asList(1, 2, 3, 4), 1));
    }

    @Test
    public void testPartition_BiggerSize() {
        List<Integer> orig = Arrays.asList(1, 2, 3, 4);
        assertEquals(
                Arrays.asList(orig),
                partition(orig, orig.size() + 11));
    }
}

Can you improve this? Are there interesting corner cases I might have missed in the tests?


texts: Adding a bookmark, or changing an existing one

texts:
I have a very problematic nested if/else/for that I'm sure it could use some love. Here's how it looks originally:

function addBookmark(obj) {
    var isFound = false;
    var posFound;
    if (bookmarks.length > 0) {
        for (var j = 0; j < bookmarks.length; j++) {
            if (obj.mirror == bookmarks[j].mirror &&
                obj.url == bookmarks[j].url &&
                obj.chapUrl == bookmarks[j].chapUrl &&
                obj.type == bookmarks[j].type) {
                if (obj.type == "chapter") {
                    isFound = true;
                    posFound = j;
                    break;
                } else {
                    if (obj.scanUrl == bookmarks[j].scanUrl) {
                        isFound = true;
                        posFound = j;
                        break;
                    }
                }
            }
        }
    }
    if (!isFound) {
        bookmarks[bookmarks.length] = {
            mirror : obj.mirror,
            url : obj.url,
            chapUrl : obj.chapUrl,
            type : obj.type,
            name : obj.name,
            chapName : obj.chapName,
            scanUrl : obj.scanUrl,
            scanName : obj.scanName,
            note : obj.note
        };
    } else {
        bookmarks[posFound].note = obj.note;
    }
    localStorage["bookmarks"] = JSON.stringify(bookmarks);
}

Is supposed to retrieve an object with bookmark information to be added/changed, loop through the array of bookmarks and check if the one we want to add exist/match, if exist then just add/change the note, if it doesn't then append.

I tried to remove chunks of it, trying to remove unnecessary nesting and this is what I achieved so far:

function addBookmark(obj) {
    var isFound = false;
    var posFound;
    if (bookmarks.length > 0) {
        for (var j = 0; j < bookmarks.length; j++) {
            if (obj.mirror == bookmarks[j].mirror &&
                obj.url == bookmarks[j].url &&
                obj.chapUrl == bookmarks[j].chapUrl &&
                obj.type == bookmarks[j].type) {
                if (obj.type == "chapter" ||
                    obj.scanUrl == bookmarks[j].scanUrl) {
                    isFound = true;
                    posFound = j;
                    break;
                }
            }
        }
    }
// more runs here, specifically the posFound/isFound variables
}

I'm thinking on replacing the break with a return statement instead and abstract the whole ifelse. Should I? Or there's a way to simplify this further?


texts:
I do not have a whole lot to do over winter break, so I wrote this little script to automate a Wordpress install (currently can only install once instance) on a fresh Debian server (tested, working with Wheezy). It may be pretty sloppy because it's the first thing I've actually tried, but it's a start I guess. I was not too worried about security with this script, but I tried to handle the passwords as best as possible, and they are not printed out at any time (except in .my.cnf, which gets deleted).

I heard somewhere that it is better to print variables like ${DOCUMENT_ROOT} instead of just $DOCUMENT_ROOT. Are there any other recommended tips like this to make scripts perform better / easier to maintain?

#!/bin/bash
#auto wordpress installer

DOCUMENT_ROOT="/var/www/wordpress"
MYSQL_ROOT_PASS="$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 16 | head -n 1)"

## uses this server email to set up apache's config file
echo "Enter in the email for the server administrator:"
read SERVER_ADMIN_EMAIL

apt-get update
apt-get upgrade

## Set up passwords so mysql-server install doesn't have password prompt
debconf-set-selections <<< "mysql-server mysql-server/root_password password $MYSQL_ROOT_PASS"
debconf-set-selections <<< "mysql-server mysql-server/root_password_again password $MYSQL_ROOT_PASS"

## install the required packages to run
apt-get -y install apache2 install libapache2-mod-php5 install libapache2-mod-auth-mysql install php5-mysql
apt-get -y install mysql-server

## download and extract wordpress
wget http://wordpress.org/latest.tar.gz
tar -xzvf latest.tar.gz

## sets up variables for wordpress installation
MYSQL_DB=wordpress$(echo "$RANDOM")
MYSQL_USER=wordpress$(echo "$RANDOM")
MYSQL_USER_PASS="$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 16 | head -n 1)"

## creates a .my.cnf so you can run mysql from the command line without password prompt
printf "[mysql]\nuser=root\npassword=\""$MYSQL_ROOT_PASS"\"\n" > ~/.my.cnf

## adds a wordpress user with own password and creates database for wordpress
mysql --defaults-file=~/.my.cnf -e "create database $MYSQL_DB; create user "$MYSQL_USER"@localhost; set password for "$MYSQL_USER"@localhost = PASSWORD(\""$MYSQL_USER_PASS"\"); GRANT ALL PRIVILEGES ON "$MYSQL_DB".* TO "$MYSQL_USER"@localhost IDENTIFIED BY '"$MYSQL_USER_PASS"'; flush privileges;"

## removes the .my.cnf file which contains mysql's root password
rm -r ~/.my.cnf

## sets up wordpress to use the newly created user and password
cp ~/wordpress/wp-config-sample.php ~/wordpress/wp-config.php
sed -i s/database_name_here/$MYSQL_DB/ ~/wordpress/wp-config.php
sed -i s/username_here/$MYSQL_USER/ ~/wordpress/wp-config.php
sed -i s/password_here/$MYSQL_USER_PASS/ ~/wordpress/wp-config.php

## puts wordpress in the appropriate place and changes permissions
mv wordpress /var/www/
sudo chown www-data:www-data /var/www/wordpress -R

## configures apache to serve wordpress as the site root
cp /etc/apache2/sites-available/default ./default.bak
sed -i s/webmaster@localhost/$SERVER_ADMIN_EMAIL/ /etc/apache2/sites-available/default
sed -i s@/\var\/www@${DOCUMENT_ROOT}@ /etc/apache2/sites-available/default
service apache2 reload

## removes the password used to do an unattended install of mysql-server
echo PURGE | debconf-communicate mysql-server

## browse to this URL to configure the wordpress install
echo "browse to the url /wp-admin/install.php to configure wordpress"


texts: Simple Cookie Service - Returns value of cookie based on cookie name passed in

texts:
Introduction

So I have written a simple service that, when loaded, reads all of the cookies in the document, reduces them to a simple object where the cookie name is the key, and the cookie value is the value, and then allows you to get a cookie by name by checking cookies[cookieName].

It works great, but I guess my biggest questions are:

Questions

Where can I improve the code of course
Is it worth optimizing the code to use a for loop instead of reduce, or is it better to leave the code more succinct by using reduce?
Will most developers know what reduce does? Should I update the code to use for simply to make it easier for other team members to understand what the code does?

But of course, feel free to pick it apart however, I'm always up for learning better ways of coding.

Other Stuff

I'm sure this code could be enhanced by allowing the setting of cookies as well, but for now my needs are simply to read cookies as my application should never be adding or modifying cookies. Therefore set functionality was intentionally left out to discourage those implementing the class from doing so.

The Code

export class CookieService {

    // Constructor
    constructor(){

        // Initialize the cookie service
        this.init()
    };

    // Holds the resulting cookies object after init is run
    cookies: any;

    // Initializes the cookie service by getting all cookies on the document and creating an object that holds each cookie by name in a key/value pair
    init: Function = () => {

        // Get the document cookie
        this.cookies = document.cookie

            // Split it on the ";" character to get each individual cookie in an array
            .split(";")

            // Reduce the array into an object
            .reduce(

                // Pass in the cookies object and the current value to the reduce callback function
                ( cookies, currentValue ) => {

                    // Split the cookie into key and value
                    let cookie = currentValue.split("=");

                    // Sanity check to make sure we got two values from the split and each value has a length.  Filters out malformed cookies.
                    if ( cookie.length === 2 && typeof cookie[0] === "string" && cookie[0].length && typeof cookie[1] === "string" && cookie[1].length ){

                        // Get the key. Trim removes any spaces from the resulting key to ensure proper matches.
                        let key = String(cookie[0]).trim();

                        // Get the value.  Trim removes any spaces from the resulting value to ensure proper matches.
                        let value = String(cookie[1]).trim();

                        // Set the new cookie on the cookies object
                        cookies[key] = value;

                        // Return the new cookies object
                        return cookies;
                    }
                }, {}
            )
    };

    // Gets a cookie from the cookies object
    getCookie: Function = cookieName => {

        // If we have a cookies array, and the requested cookie exists
        if ( typeof this.cookies !== "undefined" && this.cookies[cookieName]){

            // Return the requested cookie
            return this.cookies[cookieName];

        } else {

            // Otherwise return false to let the requester know the cookie was not found
            return false;
        }
    }
}


texts: Boiler.js Deep Object Comparison Code/Performance Optimizations?

texts:
I have a deep equality comparison method that returns true when two objects are equal (see method Doc):

_.isEqual = function (obj1, obj2) {

  // Quick compare objects that don't have nested objects
  if (_.type(obj1) === _.type(obj2) && !_.isPlainObject(obj1) && !_.isArray(obj1)) {
    switch (_.type(obj1)) {
      case "function" :
        if (obj1.toString() !== obj2.toString()) return false;
        break;
      case "nan" :
        if (obj1 === obj2) return false;
        break;
      default:
        if (obj1 !== obj2) return false;
    }
  } else {

    // When target or comparison is falsy we compare them directly
    if (_.isFalsy(obj1) || _.isFalsy(obj2)) {
      if (obj1 !== obj2) return false;
    }
    for (var o in obj1) {
      switch (true) {

        // Catch comparison of element first to prevent infinite loop when caught as objects
        case ( _.isElement(obj1[o]) ) :
          if (obj1[o] !== obj2[o]) return false;
          break;
        case ( _.isNaN(obj1[o]) ) :
          if (!_.isNaN(obj2[o])) return false;
          break;
        case ( typeof obj1[o] === "object" ) :
          if (!_.isEqual(obj1[o], obj2[o])) return false;
          break;
        case ( typeof obj1[o] === "function" ) :
          if (!_.isFunction(obj2[o])) return false;
          if (obj1[o].toString() !== obj2[o].toString()) return false;
          break;
        default :
          if (obj1[o] !== obj2[o]) return false;
      }
    }

    // Reverse comparison of `obj2`
    for (var o in obj2) {
      if (typeof obj1 === "undefined") return false;
      if (obj1 === null || obj1 === undefined) return false;
      if (_.isFalsy(obj1[o])) {
        if (_.isNaN(obj1[o])) {
          if (!_.isNaN(obj2[o])) return false;
        } else if (obj1[o] !== obj2[o]) return false;
      }
    }
  }
  return true;
};

I'm looking for advice on strategies I can use to improve its performance. My initial thoughts are get rid of my calls to internal library methods? Should I implement a different type of loop. Would a while lead to any performance gains?

After taking much of what @Joseph the Dreamer said into account I refactored _.isEqual in a seemingly much more efficient manner, which now compares the properties and values that might be attached to functions as well. As you can see I did away with a great many of my previous comparisons because they're rendered redundant in this iteration (I believe).

Here are the unit tests to back this method up: _.isEqual Unit Tests

The code:

_.isEqual = function (obj1, obj2) {
  var type = _.type(obj1), result, o;

  switch (true) {

    // Not the same TYPE
    case type != _.type(obj2) :
      return false;

    // NaNs
    case type == 'nan' :
      return _.isNaN(obj1) && _.isNaN(obj2);

    // Primitives (types that will compare correctly with ===)
    case ((typeof obj1 != 'object' && type != 'function') || type == 'null') :
      return obj1 === obj2;

    // Functions or Elements
    case type == 'function' || type == 'element' :
      return obj1.constructor === obj2.constructor;

    // JavaScript Objects
    default :
      if (_.len(obj1) == 0) {
        result = _.len(obj2) == 0;
      } else {
        for (o in obj1) {
          if (!(result = _.isEqual(obj1[o], obj2[o]))) break;
        }
      }
  }

  return result;
};


texts:
I did some looking around and found some more topics on how to use the $stmt->bind_param function inside another function or class what means the reference variables have to be sort of passed on. With the information, I obtained I was able to create a class that allows a mysqli prepared statement with fewer lines in the code itself (faster coding) and allows for error checking in the prepared statement query. I'd like to know if this method is useful and "correct" as far as code can be correct. I've planned to add more of the prepared statement's functions to the class later on but for now, this is it.

class db_prepare {

    public function __construct($query = false) {
        global $DB;
        $this->stmt = $DB->prepare($query);
        $this->error = false;
        if($this->stmt == false) {
            $this->error = true;
            echo $mysqli->error;
        }
    }

    public function bind_param($type, &...$args) {
        if($this->error == false) {
            call_user_func_array(array($this->stmt, "bind_param"), array_merge([$type], $args));
        }

    }

    public function get_result() {
        if($this->error == false) {
            $this->stmt->execute();
            return $this->stmt->get_result();
        }
    }

    public function execute() {
        if($this->error == false) {
            return $this->stmt->execute();
        }else {
            return false;
        }
    }

    public function get_result_array() {
        $array = array();
        if($this->error == false) {
            $this->stmt->execute();
            $rows = $this->stmt->get_result();
            while($row = $rows->fetch_array()) {
                $array[] = $row;
            }
        }
        return $array;
    }

    public function close() {
        $this->stmt->close();
    }

}

This means i can call upon the class in a way like this:

$query = "SELECT * FROM `reactions` WHERE `date` = ? AND `author` = ?";
$stmt = new db_prepare($query);
$stmt->bind_param("ss", $date, $author);

$date = '2018-17-07';
$author = 'Admin';
$results = $stmt->get_result();

$date = '2018-17-07';
$author = 'Mike';
$results = $stmt->get_result();
$stmt->close();


texts:
I have to wrap my text, when it's longer then 16 characters and when there is space " " or a dash "-". Can I write it with regex or a function that is easier to read than mine below?

wrapType(str) {
        if (str.length > 16) {
            var p = 16;
            while (p > 0 && (str[p] !== " " && str[p] !== "-")) {
                p--;
            }
            if (p > 0) {
                var left = (str.substring(p, p + 1) === "-") ? str.substring(0, p + 1) : str.substring(0, p);
                var right = str.substring(p + 1);
                return left + "\n" + this.wrapType(right);
            }
        }
        return str;
}


texts:
Graph Coloring Algorithm (Greedy/ Welsh Powell)

I am trying to learn graphs, and I couldn't find a Python implementation of the Welsh Powell algorithm online, so I tried to write my own. Here are the steps.

Order the nodes in descending degree. (Most neighbors ... Least neighbors)
For each node, check the colors of neighbor nodes and mark them as unavailable.
Choose the lowest available color. (from [0, 1, 2, ..., len(graph) -1])

def color_nodes(graph):
  # Order nodes in descending degree
  nodes = sorted(list(graph.keys()), key=lambda x: len(graph[x]), reverse=True)
  color_map = {}

  for node in nodes:
    available_colors = [True] * len(nodes)
    for neighbor in graph[node]:
      if neighbor in color_map:
        color = color_map[neighbor]
        available_colors[color] = False
    for color, available in enumerate(available_colors):
      if available:
        color_map[node] = color
        break

  return color_map

if __name__ == '__main__':
  graph = {
    'a': list('bcd'),
    'b': list('ac'),
    'c': list('abdef'),
    'd': list('ace'),
    'e': list('cdf'),
    'f': list('ce')
  }
  print(color_nodes(graph))
  # {'c': 0, 'a': 1, 'd': 2, 'e': 1, 'b': 2, 'f': 2}

For the input graph, it produced the above result. Is the implementation correct?


texts:
Bulls and cows is a variation of the popular game called 'Mastermind', On a sheet of paper, the players each write a 4-digit secret number. The digits must be all different. Then, in turn, the players try to guess their opponent's number who gives the number of matches. If the matching digits are on their right positions, they are "bulls", if on different positions, they are "cows"

Wikipedia page

One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equivalent score to how the last guess was scored. The next guess can be any number from the pruned list.

Either the program guess correctly or run out of numbers to guess, which indicates a problem with the scoring.

This is the implementation for n digits in C++, hunters (the list of all possible numbers that could be the answer) is a vector of string and cows it he function that counts the cows from two numbers:

for(int h=0; Hunters.size() > 1; h++){
    askBullsCows(h);
    string guess = Hunters.at(0);
    for(int i=Hunters.size()-1; i >= 0; i--){
        int pl = 0, fl = 0;
        for (unsigned int ix = 0; ix < Hunters.size(); ix++){
            if(Hunters[i].at(ix) == guess.at(ix))    pl++;
        }
        Cows(i, guess, fl);
        if((pl != P.p) || (fl != P.f)){
           Hunters.erase(cazadores.begin()+i);}
    }
}

Now, hunters (the vector) have more than 150.000 strings and it's too expensive for erase one by one string that couldn't be the answer.


texts: Visualize Parts of Song as Analyzed by Echonest

texts:
This is the a bit of code that works with Echonest API's pyechonest and remix libraries combined with matplotlib.pyplot to offer a simple visual representation of the start and end "parts" of a music track:

#!/usr/bin/env python
# encoding: utf=8
"""
mix_track_utils.py

Analyze music track using echonest API with pyechonest and remix libraries,
show parts using matplotlib graph.

"""
from __future__ import print_function
import echonest.remix.audio as audio
import matplotlib.pyplot as plt

usage = """
Usage:
    import mix_track_utils

    track1 = audio.LocalAudioFile('some.mp3')

    mix_track_utils(track1)
"""

def visualize_analysis(track):

    rates = ["tatums", "segments", "beats"]

    title = "Start and End Bits of {}".format(track.filename)
    plt.figure()
    plt.title(title)
    plt.axis([-1, 5, -3, 3])
    plt.grid(True)

    label_height = .2
    graph_height = 0
    for name in rates:
        label_height += .5
        graph_height += .5
        plt.text(0, label_height, 'Start ' + name.capitalize())
        for i in getattr(track.analysis, name)[:8]:
            j = (i.start, i.end)
            plt.plot(j,[graph_height,graph_height], linewidth=10)

    label_height = 0
    graph_height = -.2
    offset = None

    for name in rates:
        label_height -= .5
        graph_height -= .5
        plt.text(0, label_height, 'End ' + name.capitalize())
        for i in getattr(track.analysis, name)[:8]:
            j = (i.start, i.end)
            if offset is None:
                offset = j[0]
            k = (j[0] - offset, j[1] - offset)
            plt.plot(k,[graph_height,graph_height], linewidth=10)

    plt.show()

if __name__ == "__main__":
    print(usage)
    sys.exit(-1)

Getting pyechonest to work also requires adding an ECHONEST_API_KEY key to the environment, as can be seen from the links above.


texts:
I have two statements that look like this:

$('table tr td:nth-child(' + columnNumber + ')').toggle();
$('table tr th:nth-child(' + columnNumber + ')').toggle();

Is there a way to combine these two statements?


texts:
Here's the code which I use for my Android custom cursor adapter which I use to bind data to my list view.

public class MessageAdapter extends CursorAdapter {
   private Cursor mCursor;
   private Context mContext;
   private final LayoutInflater mInflater;

    public MessageAdapter(Context context, Cursor c) {
        super(context, c);
        mInflater=LayoutInflater.from(context);
    mContext=context;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {

        TextView mobileNo=(TextView)view.findViewById(R.id.mobileNolistitem);
        mobileNo.setText(cursor.getString(cursor.getColumnIndex(TextMeDBAdapter.KEY_MOBILENO)));

        TextView frequency=(TextView)view.findViewById(R.id.frequencylistitem);
        frequency.setText(cursor.getString(cursor.getColumnIndex(TextMeDBAdapter.KEY_FREQUENCY)));

        TextView rowid=(TextView)view.findViewById(R.id.rowidlistitem);
        rowid.setText(cursor.getString(cursor.getColumnIndex(TextMeDBAdapter.KEY_ID)));

    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        final View view=mInflater.inflate(R.layout.message_list_item,parent,false);
        return view;
    }

}

I know that there's another efficient way to do this which reuses the list item instantiated.  Can someone tell me how?


texts:
I want to calculate the correlation time. First I calculate the auto-correlation function:

$$
\begin{align}
\chi(t) = &\frac{1}{t_{max}-t}\sum\limits_{t'=0}^{t_{max}-t}m(t')m(t'+t)\\
&-\frac{1}{t_{max}-t}\sum\limits_{t'=0}^{t_{max}-t}m(t')\frac{1}{t_{max}-t}\sum\limits_{t'=0}^{t_{max}-t}m(t'+t)\\
&\sim e^{-t/\tau}
\end{align}
$$

The correlation-time can be calculated by fitting autocorrelation function. I.e., \$\chi(t)\$ in exponential.
For this I have written the following code:

def autocorrelation(M):
    start_time = time.time()
    tau = 1
    sweeps = len(M)
    auto = np.zeros(sweeps)
    for t in range(sweeps):
        some_time = sweeps-t
        first_term = np.average(M[:some_time]*M[t:sweeps])
        S1 = np.average(M[:some_time])
        S2 = np.average(M[t:sweeps])
        auto_temp = first_term - S1*S2
        if auto_temp > 0:
            auto[t] = auto_temp
        else:#remove oscillating part
            break
    if auto[0] != 0:
        auto = auto[auto>0]
        auto = auto/auto[0] #normalization
        len_auto = len(auto)
        if len_auto > 1: #draw a straight line if you have atleast two points
            tau = int(-1/np.polyfit(np.arange(len_auto), np.log(auto), 1, w=np.sqrt(auto))[0])
    tau = max(tau,1)
    logging.info(f"Correlation time = {tau}")
    return tau

If you put in list M = m, the function will calculate autocorrelation function and return correlation time, i.e, \$\tau\$ I also thought of using NumPy's correlate and convolve, but I could not understand them well. I tried auto_convolve = numpy.convolve(m,m,mode = "same"), after normalization, the auto/auto[0] was not same as auto_convolve/auto_convolve[0]


texts: Using record variant for register mapping in Ada

texts:
It is OK to model a double usage register with a record variant:

type Capture_Compare_Selection is (Output, Input_TI1, Input_TI2, Input_TRC) with Size=>2;
for Capture_Compare_Selection use(Output=>0, Input_TI1=>1, Input_TI2=>2, Input_TRC=>3);

type TIM_Register_CCMR (CCxS : Capture_Compare_Selection := Output) is record
   case CCxS is
      when Output=>
         OCxFE:Boolean := false;
         OCxPE:Boolean := false;
         OCMx:Output_Compare_Mode := Frozen;
         OCxCE : Boolean := false;
      when Input_TI1 .. Input_TRC =>
         ICxPSC: Input_Prescaler := P_1;
         ICxFF: Timer_Filter := No_Filter;
   end case;
end record with Size=>8;
for TIM_Register_CCMR use record
        CCxS at 0 range 0..1;
        OCxFE at 0 range 2..2;
        OCxPE at 0 range 3..3;
        OCMx at 0 range 4..6;
        OCxCE at 0 range 7..7;
        ICxPSC at 0 range 2..3;
        ICxFF at 0 range 4..7;
end record;

My rationale is that this register (well, fragment of register) has a double usage, depending on the LSB bit; it looks quite like an Ada variant record.

Is there a downside to that or can I commit all the way to this kind of use?

Here is a primer on the documentation:

The full documentation is page 344 of doc RM0090 at ST Microelectronics (huge doc).


texts:
I've written a jQuery Plugin which searches text and replaces it with other text or HTML.

Now everything works quite well, but recently I came across this SO question where the OP could have use of my plugin. That's why I linked to the GitHub repo and asked him for critiques and/or contribution.

Soon after, he said that my plugin would have slow down his page by the factor 17 (I don't think this number is coming from the dev console though). Anyway, that comment made me think about how to make my plugin faster.

(function ($) {
    "use strict";
    $.fn.replaceMe = function (options) {
        var settings = $.extend({
            textToReplace: 'any_text',
            replaceWithText: 'othertext',
            globally: true,
            excludedTags: [
                'img',
                'span'
            ]
        }, options);
        $(this).contents().each(function (index, node) {
            var text,
                excludedTags;
            if(node.innerHTML !== undefined) {
                text = node.innerHTML;
            } else {
                text = node.nodeValue;
            }
            excludedTags = (node.localName === null || node.localName === undefined) ? '' : node.localName;
            if (text.match(new RegExp(settings.textToReplace, 'g')) && node.nodeType === 3 && !excludedTags.match(new RegExp(settings.excludedTags.join('|')))) {
                if(settings.globally) {
                    $(node).replaceWith(text.replace(new RegExp(settings.textToReplace, 'g'), settings.replaceWithText));
                } else {
                    $(node).replaceWith(text.replace(new RegExp(settings.textToReplace), settings.replaceWithText));
                }
            }
        });
    }
}(jQuery));

On the testing environment, the text to parse counts 169,310 chars or 27,391 words.

The Chrome console says that the script needs 42 ms to perform. Now I'm not sure if the script needs any improvement and if yes what could be done to make it faster.


texts:
I have the method below, which generates backtesting results. However, it's highly unreadable. What could you possibly suggest to me in order to make it more readable?
public DataTable GenerateResultTable(List<BacktestResult> data)
{
    var table = new DataTable();

    table.Columns.Add("Pair");
    table.Columns.Add("Buys");
    table.Columns.Add("Avg Profit %");
    table.Columns.Add("Cum Profit %");
    table.Columns.Add($"Tot Profit {_backtestOptions.StakeCurrency}");
    table.Columns.Add("Tot Profit %");
    table.Columns.Add("Avg Duration");
    table.Columns.Add("Wins");
    table.Columns.Add("Draws");
    table.Columns.Add("Losses");

    // the number of the pairs in the backtest results
    var maxOpenOrders = data.GroupBy(e => e.Pair).Count();

    // Split results for each pair
    var query = data.GroupBy(e => e.Pair).Select(e => new { Pair = e.Key, Count = e.Count(), Value = e });

    // in case there are no records to show
    // if there are no rows, it throws an exception..
    if (!query.Any())
    {
        table.Rows.Add("", "", "", "", "", "", "", "", "", "");
    }

    foreach (var result in query)
    {
        var _profitSum = result.Value.Sum(e => e.ProfitPercentage);
        var _profitTotal = _profitSum / maxOpenOrders;

        var key = result.Pair;
        var trades = result.Count;
        var profitMean = trades > 0 ? result.Value.Average(e => e.ProfitPercentage) : 0;
        var profitMeanPercentage = trades > 0 ? result.Value.Average(e => e.ProfitPercentage) * 100 : 0;
        var profitSum = _profitSum;
        var profitSumPercentage = _profitSum * 100;
        var profitTotalAbs = result.Value.Sum(e => e.ProfitAbs);
        var profitTotal = _profitTotal;
        var profitTotalPercentage = _profitTotal * 100;
        var avgDuration = trades > 0 ? Math.Round(result.Value.Average(e => e.TradeDuration)) : 0;
        var wins = result.Value.Count(e => e.ProfitAbs > 0);
        var draws = result.Value.Count(e => e.ProfitAbs == 0);
        var losses = result.Value.Count(e => e.ProfitAbs < 0);

        table.Rows.Add(key, trades, $"{profitMeanPercentage:f2}", $"{profitSumPercentage:f2}", $"{profitTotalAbs:f8}", $"{profitTotalPercentage:f2}",
            $"{TimeSpan.FromMinutes((double)avgDuration):h\\:mm\\:ss}", wins, draws, losses);
    }

    return table;
}

public class BacktestOptions
{
    public string StakeCurrency { get; set; }
    public List<string> Pairs { get; set; }
    public string StrategyName { get; set; }
    public decimal StakeAmount { get; set; }
    public decimal OpenFee { get; set; }
    public decimal CloseFee { get; set; }
}

public class BacktestResult
{
    public string Pair { get; set; }
    public decimal ProfitPercentage { get; set; }
    public decimal ProfitAbs { get; set; }
    public decimal OpenRate { get; set; }
    public decimal CloseRate { get; set; }
    public DateTime OpenDate { get; set; }
    public DateTime CloseDate { get; set; }
    public decimal OpenFee { get; set; }
    public decimal CloseFee { get; set; }
    public decimal Amount { get; set; }
    public decimal TradeDuration { get; set; }
    public SellType SellReason { get; set; }
}

appsettings.json
{
  "BacktestConfiguration": {
    "StakeCurrency": "USDT",
    "Pairs": [ "TRXUSDT" ],
    "StrategyName": "RsiStrategy",
    "StakeAmount": 1000,
    "OpenFee": 0.001,
    "CloseFee": 0.001
  }
}


texts: Chop off trailing newline for Swift's NSAttributedString

texts:
I've made this extension but I'm touchy around NSAttributedStrings, keenly aware that Swift refuses to use the traditional notion of integer lengths on Unicode Strings, what with their graphemes that can compose and overlap. Also, it feels odd to convert to String to check for the newline. I'm not worried about \r because \n is the standard conversion when coming from HTML <p> tags. Also is this too long for something so simple? It feels like I'm missing someething

extension NSAttributedString {
    var trailingNewlineChopped: NSAttributedString {
        get {
            guard self.length > 0 else {
                return self
            }
            let lastCharRange = NSMakeRange(self.length - 1, 1)
            let lastChar = self.attributedSubstringFromRange(lastCharRange).string
            guard lastChar == "\n" else {
                return self
            }
            let mutableCopy = NSMutableAttributedString(attributedString: self)
            mutableCopy.deleteCharactersInRange(lastCharRange)
            return mutableCopy
        }
    }
}


texts:
In .NET, the SecureString type exists to prevent leaking secrets in memory. I want to create a hash from the contents of a SecureString, without putting the contents in memory in a place where I can't delete them. I have come up with the following solution, where I pinvoke the winapi crypto functions to calculate a hash over a BSTR. Does this approach make any sense? Doesn't this put the secret somewhere in memory where I can't delete it?

[DllImport("advapi32.dll", SetLastError = true)]
static extern bool Crypt...(...);

static byte[] CreateHashForSecureString(SecureString ss)
{
    IntPtr hProv = IntPtr.Zero;
    CryptAcquireContext(ref hProv, null, null, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);

    IntPtr hHash = IntPtr.Zero;
    CryptCreateHash(hProv, CALG_SHA1, IntPtr.Zero, 0, ref hHash);

    var bstr = Marshal.SecureStringToBSTR(ss);
    var len = (uint)Marshal.ReadInt32(bstr, -4);
    CryptHashData(hHash, bstr, len, 0);
    Marshal.ZeroFreeBSTR(bstr);

    byte[] pbData = new byte[20];
    uint length = (uint)pbData.Length;
    CryptGetHashParam(hHash, HP_HASHVAL, pbData, ref length, 0);

    CryptDestroyHash(hHash);
    CryptReleaseContext(hProv, 0);

    return pbData;
}

I am aware that error handling is missing. I am also aware that using SecureString is often more hasle than it's worth. I am particularly looking for whether this is the right approach to this problem.


texts:
I'm working on a function that returns a specific set of times for a given timezone and a given frequency; day, week, month.  For any given timezone and a frequency the function will return the unixtime hour start and unixtime hour end of the last full frequency given.  For example, the last full day, the last full 7 days or the last full month.

import calendar
import pytz
import time

from datetime import datetime, timedelta, time

def get_international_dates(timezone, frequency):
    tz = pytz.timezone(timezone)
    today = datetime.now(tz).date()
    midnight = tz.localize(datetime.combine(today, time(0, 0)), is_dst=True)
    last_full_day_midnight = int(midnight.astimezone(pytz.utc).strftime("%s"))
    if frequency == 'd':
        day_end = last_full_day_midnight - 3600
        day_start = last_full_day_midnight - (3600 * 24)
        prev_day_end = day_end - (3600 * 24)
        prev_day_start = day_start - (3600 * 24)
        return {'start': day_start, 'end': day_end, 'prev_start': prev_day_start, 'prev_end': prev_day_end}
    if frequency == 'w':
        week_end = last_full_day_midnight - 3600
        week_start = last_full_day_midnight - (3600 * 24 * 7)
        prev_week_end = week_end - (3600 * 24 * 7)
        prev_week_start = week_start - (3600 * 24 * 7)
        return {'start': week_start, 'end': week_end, 'prev_start': prev_week_start, 'prev_end': prev_week_end}
    if frequency == 'm':
        month_length = calendar.monthrange(today.year, today.month - 1)
        month_end = last_full_day_midnight - 3600
        month_start = last_full_day_midnight - (3600 * 24 * month_length[1])
        prev_month_end = month_end - (3600 * 24 * month_length[1])
        prev_month_start = month_start - (3600 * 24 * month_length[1])
        return {'start': month_start, 'end': month_end, 'prev_start': prev_month_start, 'prev_end': prev_month_end}

This function works as it should, but it seems pretty messy and un-pythonic.  What should I do to make this more clean, concise and pythonic?


texts: Applying same formatting to multiple borders in Excel VBA?

texts:
Is there a better way to format the cells with borders than what you get when you record a macro?  For example, I want to add borders to a cell range.  The recorded code is:

Range("A1:C19").Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With Selection.Borders(xlEdgeTop)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With Selection.Borders(xlEdgeBottom)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With Selection.Borders(xlEdgeRight)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With Selection.Borders(xlInsideVertical)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With
With Selection.Borders(xlInsideHorizontal)
    .LineStyle = xlContinuous
    .ColorIndex = 0
    .TintAndShade = 0
    .Weight = xlThin
End With

Can this be shortened?


texts:
I'm trying to unit test how my class responds to a NEST 1.7 IElasticClient's return values, using NUnit 2.6.4 and Moq 4.2. I feel mocking the Get function requires very "heavy" It.IsAny calls, and am mainly looking for feedback on how to mock IElasticClient in a way that my tests remain readable.

My code is mostly 100% actual code, with the exception of:

The Repository and Person classes are simplified (I'm mainly looking for feedback on the Test method);
I'm expecting a generic Exception but in reality I've got a custom exception class there;

Here's the code:

public class Person
{
    public string Id { get; set; }
    public string FullName { get; set; }
}

public class PeopleRepository
{
    private IElasticClient client;

    public PeopleRepository(IElasticClient Client)
    {
        this.client = Client;
    }

    public Person Get(string id)
    {
        var getResponse = client.Get<Person>(p => p.Id(id));

        if (getResponse.Source == null)
        {
            throw new Exception("Person was not found for id: " + id);
        }

        return getResponse.Source;
    }
}

[TestFixture]
public class PeopleRepositoryTests
{
    [Test]
    public void RetrieveProduct_WhenDocNotFoundInElastic_ThrowsException()
    {
        var clientMock = new Mock<IElasticClient>();
        var getRetvalMock = new Mock<IGetResponse<Person>>();

        getRetvalMock
            .Setup(r => r.Source)
            .Returns((Person)null);

        clientMock
            .Setup(c => c.Get<Person>(It.IsAny<Func<GetDescriptor<Person>, GetDescriptor<Person>>>()))
            .Returns(getRetvalMock.Object);

        var repo = new PeopleRepository(clientMock.Object);

        Assert.Throws<Exception>(() => repo.Get("invalid-id"));
    }
}

Any way I can improve the way I'm mocking IElasticClient?


texts: Keeping track of people's relationships using a people relation table

texts:
I am trying to track relationships among people. I came up with my own solution, but I'm wondering if there might be another way or better way of doing this. To keep it simplified, I'll post just the bare bones.

Let's say I have created the tables: person, person_relation, and people_relation for a MYSQL database using the following code:

DROP TABLE IF EXISTS person;
DROP TABLE IF EXISTS person_relation;
DROP TABLE IF EXISTS people_relation;

CREATE TABLE `person` (
    `id`            int(10) NOT NULL auto_increment primary key,
    `name`          varchar(32) NOT NULL,
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `people_relation` (
    `id`            int(2) NOT NULL auto_increment primary key,
    `relation`      varchar(32)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `person_relation` (
    `id`            int(10) NOT NULL auto_increment primary key,
    `parent_id`     int(10) NOT NULL,
    `child_id`      int(10) NOT NULL,
    `relation_id`   int(10) NOT NULL,
    FOREIGN KEY (`parent_id`) REFERENCES person(`id`),
    FOREIGN KEY (`child_id`) REFERENCES person(`id`),
    FOREIGN KEY (`relation_id`) REFERENCES people_relations(`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

INSERT INTO `person` (`id`, `name`)
VALUES
(1, 'John Jr'), (2, 'Jane'), (3, 'Mark'), (4, 'John'), (5, 'Betty');

INSERT INTO `people_relation` (`id`, `relation`)
VALUES
(1, 'HUSBAND'), (2, 'WIFE'), (3, 'FATHER'), (4, 'MOTHER'), (5, 'SON'), (6, 'DAUGHTER'), (7, 'GRANDFATHER'),
(8, 'GRANDMOTHER'), (9, 'GRANDSON'), (10, 'GRANDDAUGHTER'), (11, 'GREAT GRANDFATHER'),
(12, 'GREAT GRANDMOTHER'), (13, 'GREAT GRANDSON'), (14, 'GREAT GRANDDAUGHTER'), (15, 'GODFATHER'),
(16, 'GODMOTHER'), (17, 'GODSON'), (18, 'GODDAUGHTER'), (19, 'BROTHER'), (20, 'SISTER'),
(21, 'MOTHER-IN-LAW'), (22, 'FATHER-IN-LAW'), (23, 'DAUGHTER-IN-LAW'), (24, 'SON-IN-LAW');

INSERT INTO `person_relation` (`id`, `parent_id`, `child_id`, `relation_id`)
VALUES
(1, 1, 2, 1), (2, 1, 3, 3), (3, 1, 4, 5), (4, 1, 5, 5), (5, 2, 1, 2), (6, 2, 3, 4), (7, 2, 4, 23),
(8, 2, 5, 23), (9, 3, 1, 5), (10, 3, 2, 5), (11, 3, 4, 9), (12, 3, 5, 9), (13, 4, 1, 3), (14, 4, 2, 22),
(15, 4, 3, 7), (16, 4, 5, 1), (17, 5, 1, 4), (18, 5, 2, 21), (19, 5, 3, 8), (20, 5, 4, 2);

So, in my example, I am capturing 5 people, all family related, where I make connections to each of them with a unique relation: spoken plainly, a John Jr. has listed: a wife, a son, a mother, and a father; and Jane has a husband, a son, a father-in-law, and a mother-in-law, etc.

The records with 5 people end up being 20 records in the person_relation table. If I add, let's say a new daughter for John Jr. and Jane. The table will then have presumably 30 records to account all the relations.

Does this sound about right? This problem seems like it could explode to be a very large table. Do you know maybe a better way to do this? Or do you think I am on the right track?


texts: Test blank cell and out put phonetic (text)

texts:
I have this code which first checks for blank cell in Column B, and then blank cells in Column F. If the results is Yes-No, then it prints the phonetic into F.

Can someone review the code, please? I am also wondering if there is a way to set the starting point to be Column B (therefore, Cells(i,1)=B1) and possibility replace Cells(i,2) by dim as something(long?).

Sub test()

'Dim rng As Range
Dim i As Long

'Set rng = Range("B:B")
i = 1

Do Until IsEmpty(Cells(i, 2))

    If Cells(i, 2).Value <> "" Then
        If Cells(i, 6).Value = "" Then
        Cells(i, 2).Offset(0, 4).Value = Cells(i, 2).Phonetic.Text
        End If
    End If
    i = i + 1
Loop

End Sub


texts: Project Euler Problem 1 - Multiples of 3 and 5

texts:
I wrote this function for Project Euler Problem 1.

prob001 :: (Integral a) => [a] -> [a] -> a
prob001 a b = sum [x | x <- a, product ( map (x `rem`) b ) == 0]

The use is like this

GHCi> prob001 [1..999] [3, 5]
233168

But I am not at all satisfied with it. The list comprehension looks like something I have taken from Python. But I think the predicate can be much more efficient if it were written as a short-circuiting function. Currently it will have to evaluate each of these.

I am not able to think how to write that part in a short-circuiting way without a variable to hold the values. Am I correct in thinking that or not? Anything other that I can improve here?


texts: PHP function to check if something valid or return error message

texts:
I would like to make a function that checks if something is valid, but if it can't then I want to return an error message that will probably be used to to throw an exception.

public function isTodayWithinDateRange(\DateTime $start, \DateTime $end) {
    $now = new \DateTime();
    if($now >= $start && $now <= $end) return true;
    if($now < $start) return 'Today is before the start date';
    if($now > $end) return 'Today is later than the end date';
}

And would probably use within a foreach as a validation check such as...

if(isTodayWithinDateRange($myStart, $myEnd) !== true) {
    throw new Exception(isTodayWithinDateRange($myStart, $myEnd));
}

Is this a good way to go about it?  I thought about putting the exception within the function, but this doesn't seem right as all that function should be doing is doing a check and the thing calling it should decide if an error is exceptional or not.

I also thought about returning an array such as...

    return array(
        'success' => false,
        'error' => 'Today is later than the end date'
    );

But I would expect isTodayWithinDateRange to return true if the answer is 'yes'.


texts:
I'd like to improve this Insertion sort code

package com.arun.sort;

import java.util.Arrays;

public class InsertionSort {

public static void main(String[] args) {

    int[] arr = { 9, 4, 6, 2, 1, 7 };

    insertionSort(arr);
    System.out.println("Elements after sorting :" + Arrays.toString(arr));

}

public static int[] insertionSort(int[] arr) {

    int value, hole;

    for (int i = 1; i < arr.length; i++) {
        value = arr[i];
        hole = i;

        while (hole > 0 && arr[hole - 1] > value) {
            arr[hole] = arr[hole - 1];
            hole--;
        }

        arr[hole] = value;
    }
    return arr;
   }
 }


texts: Single Linked List - Improvements - 1 - not complete

texts:
TO DO

exception handling
merge with dynamic arrary

*SO Bug here--remove this line and Control K will not work

/*
Added in comments from Jerry, Ed and Loki
This code borrows from from http://cslibrary.stanford.edu/
C++ Version - lnode, lnode_reverse, lnode_push, lnode_print, lnode_count
*/
#include "c_arclib.cpp"
template <class T1> class sl_list
  {
  private:
    class node_1
      {
      public:
        T1 data;
        node_1 *next;
        node_1(T1 data, node_1 *next = NULL) : data(data), next(next) {}
      };
    node_1 *head;
    int count;
  public:
    sl_list() : count(0), head(NULL){}
    void push(int data)
      {
      node_1 *newNode = new node_1(data, head);
      ++count;
      head = newNode;
      }
    void print()
      {
      node_1 *current=head;
      while (current != NULL)
        {
        cout << current->data << endl;
        current = current->next;
        }
      }
    void reverse()
      {
      node_1 *previous, *current, *future;
      previous=NULL;
      current=head;
      future=head;
      while(current!=NULL)
        {
        future=current->next;
        current->next=previous;
        previous=current;
        current=future;
        }
      head=previous;
      }
    void break_heap()
      {
      int i=0;
      while(1)
        {
        i++;
        push(1);
        }
      }
    };
/*
C Version - lnode, lnode_reverse, lnode_push, lnode_print, lnode_count
*/

typedef struct node_type
  {
  int data;
  struct node_type* next;
  } lnode_type;

struct lnode
  {
  int data;
  struct lnode* next;
  };
void lnode_reverse(struct lnode*& head)
  {
  struct lnode *previous, *current, *future;
  previous=NULL;
  current=head;
  future=head;
  while(current!=NULL)
    {
    future=current->next;
    current->next=previous;
    previous=current;
    current=future;
    }
  head=previous;
  }
void lnode_push(struct lnode*& head, int data)
  {
  struct lnode* newNode = new lnode;
  newNode->data = data;
  newNode->next = head;
  head = newNode;
  }
void lnode_print(struct lnode* current)
  {
  while (current != NULL)
    {
    cout << current->data;
    current = current->next;
    }
  }
int lnode_count(struct lnode* current)
  {
  int count = 0;
  while (current != NULL)
    {
    count++;
    current = current->next;
    }
  return count;
  }
void break_heap()
  {
  struct lnode* head = NULL;
  int i=0;
  while(1)
    {
    i++;
    lnode_push(head,1);
    }
  }
int main()
  {
  sl_list<int> list1;
  list1.push(10);
  list1.push(20);
  list1.push(30);
  list1.push(40);
  list1.push(50);
  list1.push(60);

  list1.print();
  list1.reverse();
  list1.print();
  }


texts:
I have WCF Service.  It works fine and I want to have test coverage for it. Unit tests and acceptance.

The problem is the static class in the code.  How is it possible to avoid it?

If it will be refactored to the code without static classes - I can use mocks for example Moq.

I have also used Ninject as DI Framework so far.

    [ServiceContract]
    public interface IWorkingService
    {
        [OperationContract]
        Collection<Result> UpdateEntity(int entityID);
    }

    public class WorkingService : IWorkingService
    {
        private static readonly WorkingService Logger = ProviderLog4Net.GiveLogger(typeof(SomeService));

        /// <inheritdoc />
        public Collection<Result> UpdateEntity(int entityID)
        {
            Logger.Info("------- UpdateEntity call ------------");

            try
            {
                return CoreFacade.UpdateEntity(entityID);
            }
            catch (Exception exception)
            {
                Logger.Fatal(exception);
                throw;
            }
        }
    }

    public static class CoreFacade
    {
       ...
    }


texts: Read a single int from an optional .properties file

texts:
I am no newcomer to Java. One thing that confounds me is why it is so messy to load values from .properties files.

I have an application where, if the .properties file is found, then the value if found, should be used. And in any other circumstance, to use the default. (In the correct deployment, the server is run with sufficient permissions to engage with the socket listener 443, whereas in the development environment or any other environment where a person goes to the trouble to insert the .properties file, another port will be used).

The location of the file is com/foo/bar/webserver.properties in the in the same directory as the class file com/foo/bar/WebServer.class.

The content of webserver.properties is simply:

 listen=4444

Since this such a terribly simple function I would like to know if the community of reviewers sees a more elegant/succinct/secure/complete/correct way to load the value. I feel like I must be overlooking something basic for what feels like, to me, should be a one-liner more like the imaginary API:

    // set int value for key "listen", or else default value 443
    int port = Properties.loadProperties( "webserver.properties" ).getInt( "listen", 443 );

And here is my real code for review:

    int port;
    try ( InputStream webserverProperties = WebServer.class.getResourceAsStream( "webserver.properties" ) ) {
        if ( webserverProperties == null ) {
            port = 443;
        } else {
            Properties p = new Properties();
            p.load( webserverProperties );
            String listen = p.getProperty( "listen", "443" );
            port = Integer.parseInt( listen );
        }
    }
    catch ( NumberFormatException e ) { port = 443; }
    finally {}


texts:
I was creating some solving algorithm and write test for it. this is the tests :

    @Test
    public void test1(){
        boolean expected = true;
        int n = 7;
        DigitIncreasing digitIncreasing = new DigitIncreasing();
        assertEquals(expected,digitIncreasing.isDigitIncreasing(n));
    }

    @Test
    public void test2(){
        boolean expected = true;
        int n =36;
        DigitIncreasing digitIncreasing = new DigitIncreasing();
        assertEquals(expected,digitIncreasing.isDigitIncreasing(n));
    }

    @Test
    public void test3(){
        boolean expected = true;
        int n = 984;
        DigitIncreasing digitIncreasing = new DigitIncreasing();
        assertEquals(expected,digitIncreasing.isDigitIncreasing(n));
    }

    @Test
    public void test4(){
        boolean expected = true;
        int n = 7404;
        DigitIncreasing digitIncreasing = new DigitIncreasing();
        assertEquals(expected,digitIncreasing.isDigitIncreasing(n));
    }

    @Test
    public void test5(){
        boolean expected = false;
        int n = 37;
        DigitIncreasing digitIncreasing = new DigitIncreasing();
        assertEquals(expected,digitIncreasing.isDigitIncreasing(n));
    }

So from here I got some idea to write the test using Table driven approach like this :

     public class testObject {
        private int input;
        private boolean expected;

        public testObject(int input, boolean expected) {
            this.input = input;
            this.expected = expected;
        }

        public int getInput() {
            return input;
        }

        public boolean isExpected() {
            return expected;
        }
    }

    public void DigitIncreasing(int input, boolean expected){
        try{
            DigitIncreasing digitIncreasing = new DigitIncreasing();
            assertEquals(expected,digitIncreasing.isDigitIncreasing(input));
        }catch (AssertionError ex){
            System.out.println("input = "+input);
            System.out.println("expected = "+expected);
            ex.printStackTrace();
        }

    }

    @Test
    public void testTable(){
        testObject[] testObjects = new testObject[]{
                new testObject(7,true),
                new testObject(36,true),
                new testObject(984,true),
                new testObject(7404,true),
                new testObject(37,false),
       };

        for (testObject test : testObjects){
            DigitIncreasing(test.getInput(),test.isExpected());
        }
    }

Using Table Driven test makes me easily add another test case. any better approach or idea? since I'm adding the catch exception to get failed test.

You can find source code here.


texts:
I've just learned about custom wrapper classes and I'm a bit confused about a couple of things.
First, what's the utility of such tool? From what I understand you can mimic the copied class behaviour but with slight modifications. Is this tool used often?

Also, could you please have a look at my code? I know I'm suppose to close streams with "try with resources", but I'm not sure where it fits inside a constructor. Any other suggestions about the quality of my code are appreciated, please tear it apart!

/*
UnsupportedFileName
Change the TxtInputStream class so that it only works with txt files (* .txt).
For example, first.txt or name.1.part3.txt.
If a non-txt file is passed (e.g. file.txt.exe), then the constructor should throw
an UnsupportedFileNameException.
Think about what else you need to do if an exception is thrown.

Requirements:
x 1. The TxtInputStream class must inherit the FileInputStream class.
2. If a txt file is passed to the constructor, TxtInputStream should behave like a regular FileInputStream.
3. If a non-txt file is passed to the constructor, an UnsupportedFileNameException should be thrown.
4. If an exception is thrown, then you must also call super.close().

*/

public class TxtInputStream extends FileInputStream {
    private FileInputStream original;
    public static String fileName;

    public TxtInputStream(String fileName) throws IOException, UnsupportedFileNameException {
        super(fileName);
        if(fileName.substring(fileName.length()-4).equals(".txt")) {
            this.fileName = fileName;
        } else {
            super.close();
            throw new UnsupportedFileNameException();

        }
    }

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


texts: Efficient way to iterate over elements of array for matching contents of another array

texts:
Using jQuery I'm trying to find an efficient way to iterate through an array excludeMe and check if elements from another array needsExclusions are contained in the excludeMe array. Not sure if this is the most efficient, but it works. Fiddle here: http://jsfiddle.net/yef9q/3/

//Iterate through needsExclusions for an excludeMe string
//someFlag raised on matching strings

var excludeMe = ["in west", "philadelphia", "born and", "raised"];
var needsExclusions = ["philadelphia", "raised"];
var someFlag = true;

$.each(excludeMe, function(i,val) {
  //alert("value: " + val);
  if ($.inArray(val, needsExclusions) != -1) {
      alert("matching value: " + val);
      someFlag = false;
  }
});


texts: Rails integration testing: Should we use strings or named routes in http requests?

texts:
When integration testing Rails applications HTTP request helpers can take a string or a named route as the first argument.

I find myself writing:

test "user visits edit page" do
  homer = users(:homer)
  get "users/#{homer.id}/edit"
  assert_response :success
end

But I can also write:

test "user visits edit page" do
  homer = users(:homer)
  get edit_user_path(homer)
  assert_response :success
end

So which style should I use? And why is it preferable to the other?


texts:
I wrote a function to make a image slideshow in javascript using for() loop, setTimeout() and setInterval(), but I have doubts that is this a right approach to use a for() loop and setTimeout() together?

Is there a better way to do it...?

var myImage = document.querySelectorAll(".banner");
var arrayImage = ["https://via.placeholder.com/150x150/f00/fff?text=Slider1", "https://via.placeholder.com/150x150/f0f/fff?text=Slider2", "https://via.placeholder.com/150x150/00f/fff?text=Slider3"];
var imageIndex = 0;

function slideChange() {
  for (var i = 0; i < arrayImage.length; i++) {
    (function(i) {
      setTimeout(function() {
        myImage[i].setAttribute("src", "");
      }, 2000 * (i + 1));
      setTimeout(function() {
        myImage[i].setAttribute("src", arrayImage[i]);
      }, 2000 * i);
    })(i)
  }
}
slideChange();
setInterval(function() {
  slideChange();
}, (2000 * arrayImage.length))
.banner {
  display: block;
}


texts: Maintaining encapsulation seems to promote redundant classes

texts:
I have two classes that are extremely similar and it seems a bit redundant but I want to maintain encapsulation.

First I have a servicestack route that accepts the following Request class:

public class CreateManualShipmentRequest
{
    public Address Sender { get; set; }
    public Address Recipient { get; set; }
    public PackageSizeAndWeight Package { get; set; }
    public Payor Payor{ get; set; }

    public List<string> SpecialServices { get; set; }
    public decimal InsuredValue { get; set; }
    public string ServiceType { get; set; }
    public string ServiceProvider { get; set; }

    public string LabelImageFormat { get; set; }
    public bool TestMode { get; set; }
}

So I need to take this information and pass it to a function that creates a specific request based on the provider. For example:

FedexHelpers.BuildFedexCreateShipmentRequest();

The easiest way to pass the information I need would be to make the function accept the request object as a parameter. These seems to violate encapsulation however because the function doesn't need to know it's a request, what provider has been selected. This lead me to create a new class:

public class ShipmentRequestInfo
{
    public Address Sender { get; set; }
    public Address Recipient { get; set; }
    public PackageSizeAndWeight Package { get; set; }
    public Payor Payor { get; set; }

    public List<string> SpecialServices { get; set; }
    public decimal InsuredValue { get; set; }
    public string ServiceType { get; set; }
}

So now I can pass the builder function this object without sharing any information about the request object at all. I even created a constructor that accepts the request object:

public ShipmentRequestInfo(CreateManualShipmentRequest request)
{
    Sender = request.Sender;
    Recipient = request.Recipient;
    Package = request.Package;
    Payor = request.Payor;

    SpecialServices = request.SpecialServices;
    InsuredValue = request.InsuredValue;
    ServiceType = request.ServiceType;

    LabelImageFormat = request.LabelImageFormat;
}

I feel I have achieved encapsulation this way as I can create the ShipmentRequestInfo wherever I need but it seems redundant to have such a similar class.

I was thinking about other possibilities and came up with a few:

Have the request class contain a ShipmentRequestInfo object. This will make it harder to read, you'd have to dig into the ShipmentRequestInfo class to read the object. It would also require the JSON sent to the API route to be nested one layer further.
Overload the builder function to accept a request object or a generic object. This might cut down on a bit of code, I wouldn't need the constructor in the ShipmentRequestInfo object, and I wouldn't have to create it to pass it to the builder function. What I don't want to end up is with a function that has too many overloads though.
Have CreateManualShipmentRequest inherit ShipmentRequestInfo. I'm not sure if this is a better option than having ShipmentRequestInfo as a property of CreateManualShipmentRequest, it seems pretty similar except that it couples the classes together more tightly?

I'm pretty new to OOP and want to make sure I'm considering all my options and designing classes properly.


texts: converting object of arrays to an array of objects in a desired format

texts:
const getSelectedItemsIds = selectedItemsList => {

  let keys = Object.keys(selectedItemsList);
  let selectedItems = [];

  keys.map(k => {
    selectedItemsList[k].map(id => {
      if (k.includes("projectIds")) {
        return selectedItems.push({ type: "PROJECT", id });
      } else if (k.includes("subjectGroupIds")) {
        return selectedItems.push({
          type: "SUBJECT_GROUP",
          id
        });
      } else if (k.includes("subjectIds")) {
        return selectedItems.push({ type: "SUBJECT", id });
      }
    });
  });

  return selectedItems;
}

I have written my custom logic to get the desired result, if anyone can validate and tell me if there's a better way to do it. I'm adding input and expected out below:

I/P:
{
    projectIds: [2]
    subjectGroupIds: [] // incase multiple subjects are grouped togehter
    subjectIds: [4]
}

Expected format:
[{"type":"PROJECT","id":2},{"type":"SUBJECT","id":4}]

Thanks in advance!


texts: Calculate all possible combinations of an array of arrays or strings

texts:
I'm using code adapted from this Stack Overflow question to calculate all possible combinations from an array, which may contains strings.

For example:

[ "x", "y", "z" ] => "x y z"
[ [ "a", "b"] , "c", "d" ] => [ "a c d", "b c d" ]
[ [ "a", "b"] , ["c" "d"], "e"] => [ "a c e", "b c e", "a d e", "b d e" ]

However as the items could be strings or array I need to check for all possible combinations of array/string pairs when building the results.

This has ended in rather messy code, and I'd appreciate any hints on how to tidy it up. I've attempted to refactor it, but I guess I'm tired and missing something!

function allPossibleCases(arr) {
  if (arr.length === 0) {
    return [];
  }
  else if (arr.length === 1){
    return arr[0];
  }
  else {
    var result = [];
    var allCasesOfRest = allPossibleCases(arr.slice(1));  // recur with the rest of array

    if(typeof allCasesOfRest === 'string') {
      if(typeof arr[0] === 'string') {
          result.push(arr[0] + " " + allCasesOfRest);
      } else {
        for (var i = 0; i < arr[0].length; i++) {
            result.push(arr[0][i] + " " + allCasesOfRest);
        }
      }
    }

    else {
      for (var c in allCasesOfRest) {
        if(typeof arr[0] === 'string') {
          result.push(arr[0] + " " + allCasesOfRest[c]);
        } else {
          for (var i = 0; i < arr[0].length; i++) {
            result.push(arr[0][i] + " " + allCasesOfRest[c]);
          }
        }
      }
    }
    return result;
  }

}


texts: Declarative method to return a stack of paths

texts:
I'm building a stack of paths that each lead to a template directory. The idea is to crawl up the tree pushing paths onto the stack as long as there are contents in the template directory. This is an example file tree:

$ tree .
.
├── stack.rb
├── templates
│   ├── gem
│   │   ├── optionparser
│   │   │   └── template
│   │   │       └── foo.erb
│   │   └── template
│   │       └── foo.erb
│   └── template
└── test_stack.rb

6 directories, 4 files

This is how I am currently solving the problem:

def templates_stack template_path
  stack = []
  while Dir[template_path + "/*"].any?
    stack.unshift(File.expand_path(template_path))
    template_path = File.expand_path("../../template", template_path)
  end
  stack
end

p templates_stack("templates/gem/optionparser/template")
# => ["/Users/max/Dropbox/work/tmp/template_stack/templates/gem/template",
#     "/Users/max/Dropbox/work/tmp/template_stack/templates/gem/optionparser/template"]

The main problem is my code is not describing the real intent behind the method. The main thing I want is "a stack of paths to a template directory that all aren't empty" But I'm having trouble communicating that clearly in my code.

For example, File.expand_path("../../template"... is the only spot I really declare that I'm interested in directories named template.

Also, I'm using File.expand_path twice but in slightly different contexts. In reality I don't need the absolute path I just used it the first time because I needed a way to crawl up the tree the second time. I think the templates_stack method should actually return:

p templates_stack("templates/gem/optionparser/template")
# => ["templates/gem/template", "templates/gem/optionparser/template"]

But I'm not sure how to crawl up the tree without File.expand_path

Would love guidance on those two improvements or other areas where readability and intent can be improved.


texts: An object for passing a chain of errors in JavaScript

texts:
I want to pass errors in errors in order to know exactly the chain of causes, but without augmenting or even reading any stack until this becomes really necessary. And this is how I would achieve this:

class RError extends Error {
    constructor(options = {}) {
        super();
        this.name = options.name;
        this.message = options.message;
        this.cause = options.cause;
    }
}

Example usage:

try {
    throw new RError({
        name: 'FOO',
        message: 'Something went wrong.',
        cause: new RError({
            name: 'BAR',
            message: 'I messed up.'
        })
    });
} catch (err) {
    console.error(err);
}

Here is the result:

{ FOO: Something went wrong.
    at RError (/Users/boris/Workspace/playground/index.js:5:9)
    at Object.<anonymous> (/Users/boris/Workspace/playground/index.js:13:11)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)
    at Function.Module._load (module.js:409:3)
    at Function.Module.runMain (module.js:575:10)
    at startup (node.js:160:18)
    at node.js:456:3 name: 'FOO', message: 'Something went wrong.', cause:
   { BAR: I messed up.
       at RError (/Users/boris/Workspace/playground/index.js:5:9)
       at Object.<anonymous> (/Users/boris/Workspace/playground/index.js:16:16)
       at Module._compile (module.js:541:32)
       at Object.Module._extensions..js (module.js:550:10)
       at Module.load (module.js:458:32)
       at tryModuleLoad (module.js:417:12)
       at Function.Module._load (module.js:409:3)
       at Function.Module.runMain (module.js:575:10)
       at startup (node.js:160:18)
       at node.js:456:3 name: 'BAR', message: 'I messed up.', cause: undefined } }

Since I couldn’t find anyone on the web who uses this technique, I’m wondering if there is any drawback to this approach.

Update: I’ve created two fiddles, an es5 and an es6 version (run, see results in the console).

es5 version: https://jsfiddle.net/borisdiakur/vkj9e9fx/3/
es6 version: https://jsfiddle.net/borisdiakur/3mtfwqv1/1/

Update: I’ve created a module: https://github.com/borisdiakur/rerror


texts: Runs View Model data through concurrent service calls to get data for Entity Type

texts:
I have a few issues with the following code...

private async Task<EntityType> FillEntityDataAsync(ViewModel viewModel)
{

First, I'm thinking I need some sort of intermediate/domain model between the ViewModel and the Entity to clean this up...

    var typeAObj1 = new Response<TypeA>();
    var typeAObj2 = new Response<TypeA>();
    var typeBObj = new Response<TypeB>();
    var typeCObj = new Response<TypeC>();
    var typeDObj = new Response<TypeD>();

...except I'd like to try and run the following service calls concurrently, which would make the preceding types:

Task<Response<TypeA>>

etc. Normally I'd just do Task.WhenAll() for the calls, but I think the conditional blocks are tripping me up.

    typeAObj1 = await _someService.GetTypeAData();

    if(!string.IsNullOrWhiteSpace(viewModel.vmProp1)
    {
        typeBObj = await _someService.GetTypeBData();
        typeCObj = await _someService.GetTypeCData();
        typeDObj = await _someService.GetTypeDData();
    }
    else if(!string.IsNullOrWhiteSpace(viewModel.vmProp2)
    {
        typeAObj2 = await _someService.GetTypeAData(viewModel.vmProp2);
    }

    var newEntityObj = new EntityType
    {
        SomeProperty = "",
        AnotherProperty = typeAObj1.Data?.Property1,
        AThirdProperty = typeAObj2.Data?.Property2,
        Prawpertee = typeBObj.Data?.TypeBProp,
        LastOne = typeCObj.Data?.TypeCProp,
        JustKidding = typeDObj.Data?TypeDProp
    }

    return newEntityObj;
}

So I'm trying to clean this code up, and figure out the best way of running these calls concurrently. How do you suggest going about that? Thanks for your time.


texts: get city and state using zip code, scrape in Python

texts:
I'm looking for any and all feedback on quality, style and efficacy of the code. If there's a simple way to get the header put in, I'd love to hear that.

The code is used to take zip codes from a csv file and and spit back out the city and state where available.

import sys
import os
import csv
from bs4 import BeautifulSoup
import requests

def main():
    pass

def getCityState(zipCode):
# given zip code, return city and state if available
    zipCode = str(zipCode)
    url = "http://www.city-data.com/zips/" + zipCode + ".html"
    r = requests.get(url)
    data = r.text
    soup = BeautifulSoup(data)
    if soup.findAll(text="City:") ==[]:
        cityNeeded = soup.findAll(text="Cities:")
        for t in cityNeeded:
            return t.find_next('a').string

    else:
        cityNeeded = soup.findAll(text="City:")
        for t in cityNeeded:
            return t.find_next('a').string

def getTableFromCSV(fileName, settings):
    with open(fileName, settings) as fp:
        reader = csv.DictReader(fp, skipinitialspace=True)
        table = [row for row in reader]
        header = reader.fieldnames
    return header,table # header and table are lists of dicts

def printTable(header, table):
# print table in console
    print"begin printTable"
    for row in table:
        print row
    print"end printTable"

def addToList(theList, position, newItem):
    theList.insert(position, newItem)
    return theList

def addToDict(theDict, newKey, newItem):
    theDict[newKey] = newItem
    return theDict

def checkZips(table):
# check zips and insert the city and town if there is a good zip
    for row in table:
        stringNeed = row['zip']
        if not stringNeed.isdigit(): # check to see if it's a number
            row["cityState"] = "zip not number"
            pass
        else:
            if not len(stringNeed) == 5:  #check to see if it's 5 digits long
                row["cityState"] = "zip not 5 digits"
            else:
                cityState = getCityState(stringNeed)
                row["cityState"] = cityState
                # print row
     return table

if __name__ == '__main__':
    print"begin main"

    # get table from csv file
    header, table = getTableFromCSV("propertyOutputTest.csv","rUbw")

    # add city, state to header
    header.insert(0,"cityState")

    #check zips and insert city and state whree available
    checkZips(table)

    # write table to a csv file that replaces the old csv file
    with open("propertyOutputTest.csv","wb") as fp:
        writer = csv.DictWriter(fp, header)
        for row in table:
            writer.writerow(row)

    print"end main"


texts: Is it a good idea to keep Request querystring as a property?

texts:
My code snippet is like this:

public static string EventId
{
    get { return HttpContext.Current.Request["eventId"]; }
}

And I will call this property EventId whenever I need it. Is it a good practice?


texts:
public function getStuff($brand)
{
    $web=FALSE;
        if($this->getWebcorners()):
            foreach ($this->getWebcorners() as $webcorner):
                if(strtolower($webcorner->getBrand()->getName())== $brand):
                    return $webcorner;
                endif;
                if($webcorner->getBrandId()==NULL):
                    $web=$webcorner;
                endif;
            endforeach;
        endif;
    return $web;
}

the function is suppose to list a collection of webcorners and return the first that matches a brand, then the one that is null (in this order).  There's a possibility to have many other webcorners according to the brand (but no matching the one that is passed by parameter to the function).


texts: Updating tables with bulk of data through CSV

texts:
My work is pretty simple.  I have to migrate a bulk of data into the specified tables, so that the data does show up at the front-end.  The data is provided through the Excel sheet and I have to convert it into a CSV file with $ as a field delimiter.

And later I have to write a method in an Active Record Model to perform the migration.

def self.discipline_and_speciality_migration_21Jan14

  filename = "#{RAILS_ROOT}/config/discipline_and_speciality_migration_220114.csv"
  file=File.new(filename,"r")

  while (line = file.gets)
  columns = line.split("$")

  location = Location.find_by_name(columns[2].to_s.chomp.strip)
  if location.blank?
  location = Location.create!(:name => columns[2].to_s.chomp.strip,:short_name => columns[2].to_s.slice(0,11) , :status => "Active")
   end

   discipline = Discipline.find_by_name_and_location_id(columns[0].to_s.chomp.strip,location.id)
   if discipline.blank?
   discipline = Discipline.create!(:name=>columns[0].to_s.chomp.strip,:status=>'Active',:location_id => location.id,:code=> columns[1].to_s.chomp.strip)
    else
    discipline.update_attributes(:location_id => location.id)
    end

    speciality = Speciality.find_by_name_and_location_id(columns[3].to_s.chomp.strip)
    if speciality.blank?
    speciality = Speciality.create!(:name => columns[3].to_s.chomp.strip,:status=>'Active',:location_id => location.id,:code=> columns[4].to_s.chomp.strip,:discipline_id => discipline.id)
     else
     speciality.update_attributes(:location_id => location.id,:discipline_id => discipline.id)
     end
    end
    end

I have no Issues with the code.  I am just wondering is there any better approach to do this.  Is CSV the only way? Notable modifications in the code are also welcomed.


texts:
Problem Statement:

  Create a class diagram and Java code for the following system and
  scenario, taking into account the possibility of future extensions.
  "The system is a command line utility that prints a short 'quote of
  the day' on the user's terminal when run. To begin with the quote is
  selected randomly from a set of hard-coded strings within the program
  itself, but that might change later on -- the quotes might be based on
  the user's history, the time of day, the date, etc.. Scenario:

  User types "java QuoteOfTheDay" on the command line.
  System prints out a quote of the day, with an attribution.

This is my code for the following:

package quoteOfTheDay;
import java.util.Random;

public class QuoteOfTheDay {

    public static void main(String[] args) {

        System.out.println();

        Random rand = new Random();
        int randomInt = rand.nextInt(20);

        switch (randomInt) {
        //Print a quote depending upon the generated random number..
        }
    }
}

Is this the right approach? Am I missing some things from the problem requirements? I am open for any kind of suggestions.


texts:
1 REM
2 REM FIZZBUZZ IN COMMODORE BASIC
3 REM
10 FOR I = 1 TO 100
20 IF (I/3)=INT(I/3) THEN PRINT "FIZZ";
30 IF (I/5)=INT(I/5) THEN PRINT "BUZZ";
40 IF (I/3)<>INT(I/3) AND (I/5)<>INT(I/5) THEN PRINT I;
50 PRINT
60 NEXT I

I'm not happy with the tests for "multiple of 3" and "multiple of 5".  Using floating-point arithmetic to determine integer multipleness feels highly inelegant, but I don't believe Commodore Basic has "integer mod" functionality, and I can't think of another similarly-compact way to determine that one integer is a multiple of another.
When run using the VICE emulator, it takes almost nine seconds to execute.  Besides getting rid of the floating-point division, are there any obvious ways to speed things up?


texts:
I've just tried to do some code for TreeMap. The TreeMap concept can be found here. As an exercise I've tried to find the solution without reading the article.

Then, I came across this code. The main problem is that I missed the algorithm, my code is not so simple, elegant, short and clean. And I used OOP because I didn't know how to do without it (at university I learned no C, no functional programming, only OOP).

Another issue is that I wanted to make a list of rectangles with no dependencies from the render engine (no matplotlib, maybe I'm writing something for openGL and pyqt), so I need some Rectangle with coordinates normalized between 0 and 1.

This is my code, which I'm no proud of: it is too verbose, redundant and not KISS, and maybe it could also be a bit more readable:

class Rectangle(object):

    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height

    def __repr__(self):
        return "Rect - x:{0}, y:{1}, width:{2}, height:{3}".format(self.x, self.y, self.width, self.height)

class Node(object):
    iter_method = iter
    size_method = int

    def __init__(self, content, depth=0):
        self.depth = depth
        self.childs = []
        try:
            self.value = Node.size_method(content)
        except TypeError:
            self.childs = [Node(x, depth+1) for x in Node.iter_method(content)]
            self.value = sum(child.value for child in self.childs)

    @property
    def leaf(self):
        return len(self.childs)>0

    def __repr__(self):
        s = "{0}Node:{1}".format('\t'*self.depth, self.value)
        if self.leaf:
            s += '\n'+'\n'.join(str(child) for child in self.childs)
        return s

class TreeMap(object):

    def __init__(self, root):
        self.root = root

        self.rects = []
        self.build(self.root, Rectangle(0,0,1,1))

    def build(self, node, rect, horizzontal=True):
        node.rect = rect
        self.rects.append( rect )

        sizes = [child.value for child in node.childs]
        total_size = node.value

        if horizzontal:
            x = 0.0
            for child in node.childs:
                y = rect.y
                w = (child.value*rect.width) / float(total_size)
                h = rect.height
                self.build(child, Rectangle(x,y,w,h), not horizzontal)
                x += w
        else:
            y = 0.0
            for child in node.childs:
                x = rect.x
                h = (child.value*rect.height) / float(total_size)
                w = rect.width
                self.build(child, Rectangle(x,y,w,h), not horizzontal)
                x += w

import unittest

class Test_TreeMap(unittest.TestCase):

    def test_build_depth0(self):
        nodes = (2,1,(2,2))

        known = (1,     1), (2.0/7, 1), (1.0/7, 1), (4.0/7, 1), (4.0/7, 0.5), (4.0/7, 0.5)

        Node.iter_method = iter
        Node.size_method = int
        root = Node(nodes)

        t = TreeMap(root)
        widths = tuple((rect.width, rect.height) for rect in t.rects)
        self.assertEqual(known, widths)
unittest.main()


texts:
I have a GiftCard class where I have method can_deliver? and deliver! that I think can be refactored to better looking code :

  def can_deliver?
    (self.sent_at.nil? && self.scheduled_at.nil?) || (self.sent_at.nil? && self.scheduled_at && self.scheduled_at < Time.now)
  end

  def deliver!
    return unless self.can_deliver?
    begin
      Notifier.gift_card_code_mail(self).deliver
      self.sent_at = Time.now
      self.save
    rescue Exception
      logger.error "Could not send email gift card ##{self.id}"
      self.line_item.order.comments.create!(:content => "Can not send gift card mail")
    end

    begin
      Notifier.gift_card_delivered(self).deliver
    rescue Exception
      logger.error "Could not send deliver confirmation email gift card #{self.id}"
      self.line_item.order.comments.create!(:content => "Can not send confirmation delivery of gift card")
    end

  end


texts:
I want to display multiple radio buttons in a layout with multiline style as an item inside a RecyclerView. Look at the code I provided below and suggest how I can refactor the code to be more efficient or optimized:

Layout in XML:

<RadioButton
    android:id="@+id/rb_rad1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/dp_10"
    android:checked="true"
    android:text="@string/text1"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/xyz" />

<RadioButton
    android:id="@+id/rb_rad2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="@dimen/dp_34"
    android:checked="false"
    android:text="@string/text2"
    app:layout_constraintBaseline_toBaselineOf="@+id/rb_rad1"
    app:layout_constraintLeft_toRightOf="@+id/rb_rad1" />

<RadioButton
    android:id="@+id/rb_rad3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="false"
    android:text="@string/text3"
    app:layout_constraintLeft_toLeftOf="@+id/rb_rad1"
    app:layout_constraintTop_toBottomOf="@+id/rb_rad1" />

<RadioButton
    android:id="@+id/rb_rad4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="false"
    android:text="@string/text4"
    app:layout_constraintLeft_toLeftOf="@+id/rb_rad2"
    app:layout_constraintTop_toBottomOf="@+id/rb_rad2" />

Inside the onBindViewHolder() method:

holder.binding.rbRad1.setOnClickListener(object : View.OnClickListener {
                override fun onClick(view: View?) {
                    holder.binding.rbRad2.isChecked = false
                    holder.binding.rbRad4.isChecked = false
                    holder.binding.rbRad3.isChecked = false
                    notifyDataSetChanged()
                }
            })

            holder.binding.rbRad3.setOnClickListener(object : View.OnClickListener {
                override fun onClick(view: View?) {
                    holder.binding.rbRad2.isChecked = false
                    holder.binding.rbRad4.isChecked = false
                    holder.binding.rbRad1.isChecked = false
                    notifyDataSetChanged()
                }
            })

            holder.binding.rbRad2.setOnClickListener(object : View.OnClickListener {
                override fun onClick(view: View?) {
                    holder.binding.rbRad3.isChecked = false
                    holder.binding.rbRad4.isChecked = false
                    holder.binding.rbRad1.isChecked = false
                    notifyDataSetChanged()
                }
            })

            holder.binding.rbRad4.setOnClickListener(object : View.OnClickListener {
                override fun onClick(view: View?) {
                    holder.binding.rbRad2.isChecked = false
                    holder.binding.rbRad3.isChecked = false
                    holder.binding.rbRad1.isChecked = false
                    notifyDataSetChanged()
                }
            })


texts: Float to Byte Array Serialization Over Network

texts:
I wrote this code for a multiplayer game I am developing to transmit floats over the network. It works, on the systems that I have tested it with. What I am worried about is the little-endian big-endian thing and the possibility of different float representations in general over computers. So here it goes:

private static ByteFloat bytefloat = new ByteFloat();
[StructLayout(LayoutKind.Explicit)] struct ByteFloat
{
    [FieldOffset(0)] public float v;
    [FieldOffset(0)] public byte a;
    [FieldOffset(1)] public byte b;
    [FieldOffset(2)] public byte c;
    [FieldOffset(3)] public byte d;
}
public void setFloat(float v)
{
    bytefloat.v = v;
    setByte(bytefloat.a);
    setByte(bytefloat.b);
    setByte(bytefloat.c);
    setByte(bytefloat.d);
}
public float getFloat()
{
    bytefloat.a = getByte();
    bytefloat.b = getByte();
    bytefloat.c = getByte();
    bytefloat.d = getByte();
    return bytefloat.v;
}

I don't really want advice on variable naming or coding conventions, I just want to know if there are possible flaws with this code when the methods are called on different systems. I want to know if calling setFloat on some float, and sending the resulting bytes to any other computer, then calling getFloat on those bytes will result in the exact same value that I started with.

getByte() and setByte() do exactly what they say they do, this method pertains to a class which is a byte array wrapper, used for reading and writing data. (The backing byte array is sent over the network, and on the receiving side it is wrapped again and read from.)

If this code does not work across all systems, I would like a recommendation (or a solution) on how to write it in a way that is cross-system.

If this changes anything, I am working with the Unity platform and it's networking LLAPI (Raknet).


texts: Regex to obtain float values from a large text file

texts:
I am reading a text file and obtaining certain data from the file. The following line is repeated over a million times in the file where the £ values may differ each time.

  Start Game, Credit: £200.00game num: 1, Stake:
  £2.00Spinning Reels:NINE SEVEN KINGKING STAR ACEQUEEN JACK KINGtotal
  winnings: £0.00End Game, Credit: £198Start...

I only want the Stake and winning values each time. Written following code to read the text file and extract the information and it is working. I get the results pretty much instantly.

I have concerns on whether the group input for the method is difficult to understand or maybe a better way to define it? As for regex, I am checking for (Stake: £) for readability instead of (e: £) which would have worked too. Is there a performance difference between this 2 checks?

Can I get feedback on whether the regex could have been done in a more optimal way or anyway I could improve the code at all be it remove unnecessary checks or use better methods. Thanks.

Data Class which has methods to read text file / do regex check

public class Data {

    /**
     * @param fileName name of text file to read
     * @return return the string containing the read file data
     */
    public StringBuilder FileData(String fileName){

        StringBuilder sb = null;

        try(BufferedReader br = new BufferedReader(new FileReader(fileName))) {

            sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                line = br.readLine();
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }

        return sb;
    }

    /**
     * @param pattern pattern to search for
     * @param group determine which group from pattern to add to list
     * @return all data that matches the pattern
     */
    public List<Double> RegexCheck(String line, String pattern, int group){

        List<Double> ls = new ArrayList<>();

        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(line);

        while (m.find()){
            ls.add(Double.valueOf(m.group(group)));
        }

        return ls;
    }
}

Main Class where stakes / winnings are added to display total

public static void main(String[] args) {

    Data data = new Data();

    //read and store file data
    StringBuilder fileData = data.FileData("myfile.txt");

    //obtaining all stake values
    List<Double> stakes = data.RegexCheck(fileData.toString(), "(Stake: £)(\\d+(?:\\.\\d+)?)", 2);

    //Adding all stake values together for total stake value
    double totalStake = 0;
    for(double d : stakes){
        totalStake+= d;
    }

    //obtaining all winning values
    List<Double> winnings = data.RegexCheck(fileData.toString(), "(winnings: £)(\\d+(?:\\.\\d+)?)", 2);

    //Adding all winning values together for total winning value
    double totalWinning = 0;
    for(double d : winnings){
        totalWinning+= d;
    }

    System.out.println("The total stakes gambled is: " + totalStake);
    System.out.println("The total winnings gambled is: " + totalWinning);
}


texts: Printing Colored, CLId Unicode Chess Board - follow-up

texts:
Follow up to: Printing Command Line Unicode Chess Board

A couple people from the previous question mentioned looking into coloring the command line with ANSI escape sequences. In Python, colorama seems to handle this quite nicely. Below is my attempt at using it for printing out a chess board.

from enum import Enum
from enum import auto
from colorama import init, Fore, Back, Style

class Color(Enum):
    WHITE = 0
    BLACK = 1

class Piece(Enum):
    EMPTY = auto()
    PAWN = auto()
    ROOK = auto()
    KNIGHT = auto()
    BISHOP = auto()
    KING = auto()
    QUEEN = auto()

ELEMENTS = {
    (Color.WHITE, Piece.EMPTY): Back.WHITE,
    (Color.WHITE, Piece.KING): f'{Fore.LIGHTWHITE_EX}\u265A',
    (Color.WHITE, Piece.QUEEN): f'{Fore.LIGHTWHITE_EX}\u265B',
    (Color.WHITE, Piece.ROOK): f'{Fore.LIGHTWHITE_EX}\u265C',
    (Color.WHITE, Piece.BISHOP): f'{Fore.LIGHTWHITE_EX}\u265D',
    (Color.WHITE, Piece.KNIGHT): f'{Fore.LIGHTWHITE_EX}\u265E',
    (Color.WHITE, Piece.PAWN): f'{Fore.LIGHTWHITE_EX}\u265F',
    (Color.BLACK, Piece.EMPTY): Back.LIGHTBLACK_EX,
    (Color.BLACK, Piece.KING): f'{Fore.BLACK}\u265A',
    (Color.BLACK, Piece.QUEEN): f'{Fore.BLACK}\u265B',
    (Color.BLACK, Piece.ROOK): f'{Fore.BLACK}\u265C',
    (Color.BLACK, Piece.BISHOP): f'{Fore.BLACK}\u265D',
    (Color.BLACK, Piece.KNIGHT): f'{Fore.BLACK}\u265E',
    (Color.BLACK, Piece.PAWN): f'{Fore.BLACK}\u265F'
}

def init_tiles():
    row = [ELEMENTS[(Color(i % 2), Piece.EMPTY)] for i in range(8)]
    return [row if i % 2 == 0 else row[::-1] for i in range(8)]

def init_board():

    def get_army(color):
        return [
            (color, Piece.ROOK),
            (color, Piece.KNIGHT),
            (color, Piece.BISHOP),
            (color, Piece.QUEEN),
            (color, Piece.KING),
            (color, Piece.BISHOP),
            (color, Piece.KNIGHT),
            (color, Piece.ROOK)
        ]

    return (
        [
            get_army(Color.BLACK),
            [(Color.BLACK, Piece.PAWN) for _ in range(8)],
            *[[None] * 8 for _ in range(4)],
            [(Color.WHITE, Piece.PAWN) for _ in range(8)],
            get_army(Color.WHITE)
        ]
    )

def print_board(board, flip=False):

    def flip_board(board):
        return [row[::-1] for row in reversed(board)]

    for i, row in enumerate(board if not flip else flip_board(board)):
        for j, piece in enumerate(row):
            piece = ELEMENTS.get(piece)
            print(f"{tiles[i][j]}{piece if piece else ' '}",
                  Style.RESET_ALL, end='', flush=True)
        print()

if __name__ == '__main__':
    init()
    tiles = init_tiles()
    board = init_board()
    print_board(board)

As always, any optimizations and critique is welcome!

Example Output:


texts:
I'm posting a solution for LeetCode's "Maximal Network Rank". If you'd like to review, please do so. Thank you!
Problem
There is an infrastructure of n cities with some number of roads connecting these cities. Each roads[i] = [ai, bi] indicates that there is a bidirectional road between cities ai and bi.
The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once.
The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities.
Given the integer n and the array roads, return the maximal network rank of the entire infrastructure.
class Solution:
    def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:
        indegrees = collections.defaultdict(list)
        for i in range(n):
            for a, b in roads:
                if i == a:
                    indegrees[i].append(f'{i}-{b}')
                    indegrees[i].append(f'{b}-{i}')
                if i == b:
                    indegrees[i].append(f'{i}-{a}')
                    indegrees[i].append(f'{a}-{i}')

        max_net = 0
        for i in range(n):
            for j in range(n):
                if f'{i}-{j}' or f'{j}-{i}' in indegrees[i]:
                    net = len(set(indegrees[i] + indegrees[j])) // 2
                    max_net = max(max_net, net)

        return max_net


texts:
After reading this question, I've realized that I can do a lot to improve the quality of my question, so I've edited this question quite a bit.

I've been teaching myself F# in my spare time off and on for the last 6 months.  I've finally started getting comfortable enough with the language to feel that a lot of my code could be much better.  The problem is, I don't know what changes to make.

Here's what I'm interested in:

I'm using higher order functions to return functions for interacting with a specific message queue.  Is this a good design.  Would another F# developer feel comfortable with this?
Does this fit the idiomatic style of F#?
If you know RabbitMQ, are there any bugs which I may be creating here.

Here's the context of the little block of code:

I'm doing a lot of experiments with messaging systems and I've been using RabbitMQ as a messaging framework.  There's a .Net library for RabbitMQ but it's written in and for C#.  I can use it in F# but it feels clunky.  I wanted a small wrapper around the RabbitMQ library which which convert it into a more functional interface.  Also, this will hopefully make it very easy to use RabbitMQ in an F# program.

My wrapper handles the following for RabbitMQ:

Connect to a RabbitMQ server
Create a function which will let you read one message from a queue
Create a function which will write a message to a queue
For both 2 and 3, if the queue doesn't exist, the queue will be created (that's the declareQueue)

module Client =
    let connectToRabbitMqServerAt address =
        let factory = new ConnectionFactory(HostName = address)
        factory.CreateConnection()

    let openChannelOn (connection:IConnection) = connection.CreateModel()

    let private declareQueue (channel:IModel) queueName =
        channel.QueueDeclare( queueName, false, false, false, null )

    let private publishToQueue (channel:IModel) queueName (message:string) =
        let body = Encoding.UTF8.GetBytes(message)
        channel.BasicPublish("", queueName, null, body)

    let createQueueReader channel queue =
        declareQueue channel queue |> ignore

        fun () ->
            let ea = channel.BasicGet(queue, true)
            if ea <> null then
                let body = ea.Body
                let message = Encoding.UTF8.GetString(body)
                Some message
            else
                None

    let createQueueWriter channel queue =
        declareQueue channel queue |> ignore
        publishToQueue channel queue

An example use case would be:

// open a connection to a RabbitMQ broker
let connection = connectToRabbitMqServerAt "localhost"
let myChannel = openChannelOn connection

// Connect to a queue for writing
let writeToHelloQueue = createQueueWriter myChannel "hello"

// write the message "Hello, World" to the queue "hello"
"Hello, World" |> writeToHelloQueue