Saturday, August 29, 2015

Dynamic input list in Aurelia

I struggled with getting this dynamic form pattern figured out in Aurelia so I'm sharing it here for myself in the future and others that might find it useful.

The features needed are:
  • Automatically add new blank input fields at the end of the list as needed
  • Allow the removal of any items from the list at any point
  • Allow changing any items in the list of inputs

Given lots of help from the Aurelia Gitter channel especially by Jeremy Danyow (@jdanyow) and Io Sulfur (@iosulfur) who created several Plunkrs zeroing in on the right solution, we came up with this approach as demonstrated in the Plunkr below.

Anytime you change the blank item field at the end, it will add another empty input field at the end. If you click on the 'X' button, it will remove that item.

Demo Plunkr

The key things to note in the app.html listing below are that the 'items' in line 6 must be your actual array.  If this is in a nested repeat.for loop and items is made available from the parent repeat.for, this approach will not update the original array only the one that is local to the repeat.for context.

The change.delegate on line 8 adds the blank line using the current index value of the repeat and the change event.  You'll see how they are used in the app.js file below.

The click.delegate very simply removes the input field by splicing out that item from the items array.


The first thing to do is to add a blank item at the end of the items array before we even present it to the View in line 7 of app.js

The addBlank function first sets the current item (based on the $index value passed from the change.delegate function) to the and then blanks out the  We blank out the as otherwise that value gets added to the end of the list of input fields.

We then check to see if the last input field is empty or not, and if it returns true, we push an empty string onto items.  (Note: if anyone can explain why you get the instead of the empty '' string unless we reset the, please post it in the comments - because I've not been able to figure it out.

The removeItem is pretty self-explanatory - so that's all.  Thanks for reading, hope it is useful.

Added (2015-08-30) :  When I tried this with an object as the item, I didn't need lines 12 and 13 in app.js.


Friday, August 21, 2015

Logging in Aurelia

Just some quick notes on setting up logging in Aurelia

Add customer log appender

Create a file in ./resources/custom-log-appender.js and add the following class (or any other file as long as you change the import in the main.js file).

export class CustomLogAppender {
constructor(){} debug(logger, message,{ console.debug(`DEBUG [${}] ${message}`,; } info(logger, message,{`INFO [${}] ${message}`,; } warn(logger, message,{ console.warn(`WARN [${}] ${message}`,; } error(logger, message,{ console.error(`ERROR [${}] ${message}`,; } }

Update your main.js

import {LogManager} from 'aurelia-framework';
import {CustomLogAppender} from './resources/custom-log-appender';

LogManager.addAppender(new CustomLogAppender());

export function configure(aurelia) {
    // .developmentLogging()

  aurelia.start().then(a => a.setRoot());

and in your View Model

# ViewModel
import {LogManager} from 'aurelia-framework';
let logger = LogManager.getLogger('viewmodulename');

export class MyViewModel() {“Hah”);

Tuesday, August 18, 2015

Enabling ES2016(ES7) Async functions in Aurelia

I was having a lot of problems getting the Javascript ES2016 (ES7) async functions working in Aurelia. I knew I had to update the config.js code in Aurelia by adding es7.asyncFunctions:

defaultJSExtensions: true,
transpiler: "babel",
babelOptions: {
"optional": [

I then tried to add my async method function to an Aurelia ViewModel:

async activate () {
try {
this.results = await;
console.log(`Search results: ${this.results.evidence}`);
catch (err) {

and promptly got this error in my javascript console after the page loaded:

ERROR [app-router] ReferenceError: regeneratorRuntime is not defined

Jeff Bellsey (@jbellsey) on Gitter -> Aurelia/Discuss was kind enough to figure out the issue and share it with me.  I was not however smart enough to understand the answer at the time. He told me I had to add the runtime to the babel-options file (<AureliaProjectRoot>/build/babel-options.js):

module.exports = {
modules: 'system',
moduleIds: false,
comments: false,
compact: false,
optional: [

The “runtime” and “es7.asyncFunctions” lines need to be added to the file.

This was a LOT of fun to sort out.  However, I now have, for me, much more understandable code using the async, try, await, catch format.  Thank you Jeff and the other fantastic Aurelians!




Tuesday, February 3, 2015

Python SSH Tunnel Example

Notes for myself and hopefully others.
def createTunnel(localport, remoteport, identityfile, user, server):
    """Create SSH Tunnels for Database connections"""

    import shlex
    import subprocess
    import time

    sshTunnelCmd = "ssh -N -L %s: -i %s %s@%s" % (
		localport, remoteport, identityfile, user, server

    args = shlex.split(sshTunnelCmd)
    tunnel = subprocess.Popen(args)

    time.sleep(2)  # Give it a couple seconds to finish setting up

    return tunnel  # return the tunnel so you can kill it before you stop
				   # the program - else the connection will persist 
				   # after the script ends

def closeSSHTunnel(tunnels):
    """Close SSH tunnels - given the process handles"""

    for tunnel in tunnels:

localport = 27018  # local port for MongoDB
remoteport = 27017  # remote server port for MongoDB
identityfile = '/home//.ssh/id_rsa.pem'
user = 'ubuntu'
server = ''

# Start tunnel
tunnel = createTunnel(localport, remoteport, identityfile, user, server)

	# Example usage
	db_server = 'localhost'
	db_port = 27018
	client = pymongo.MongoClient('mongodb://{}:{}'.format(db_server, db_port))
	pydb = client.agencies


Monday, January 19, 2015

Installation Notes for Flask App on Ubuntu 14.04 LTS using gUnicorn

Installation Notes for Flask App on Ubuntu 14.04 LTS using gUnicorn

Followed these excellent directions from Real Python and modified for python3 and Ubuntu 14.04.
Start with updating ubuntu and loading additional packages
sudo apt-get updatesudo apt-get install -y python3 python3-pip nginx mongodb supervisorsudo pip3 install virtualenv
sudo mkdir /var/wwwsudo chown ubuntu:ubuntu /var/wwwmkdir /var/www/flask-appmkdir /var/www/flask-app/logscd /var/www/flask-app

Setup virtualenv
virtualenv flask_env
source flask_env/bin/activate
pip install -r requirements.txt
pip install gunicorn

Setup nginx

sudo /etc/init.d/nginx start
sudo rm /etc/nginx/sites-enabled/default
sudo touch /etc/nginx/sites-available/flask-app
sudo ln -s /etc/nginx/sites-available/flask-app /etc/nginx/sites-enabled/flask-app
sudo vim /etc/nginx/sites-enabled/flask-app
Add the following to the nginx flask-app conf file being edited
server {
    location / {
    location /static {
        alias  /var/www/flask-app/flAsk-app/static;

sudo service nginx reload

Setup gunicorn start file

Setup bash script to run gunicorn
cd /var/www/flask-app
touch gunicorn_start
chmod a+x gunicorn_start
vim gunicorn_start
Insert the following into the gunicorn_start bash script

NUM_WORKERS=3 echo "Starting $NAME" # activate the virtualenv cd $VENVDIR source bin/activate export PYTHONPATH=$FLASKDIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start your unicorn exec gunicorn runserver:app -b \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --log-level=debug \

Setup Supervisor

This will run and restart the Flask application when the application files are changed.
cd /etc/supervisor/conf.d
sudo vim flask-app.conf
Insert the following into the flask-app.conf file:
command = /var/www/flask-app/gunicorn_start
user = ubuntu
stdout_logfile = /var/www/flask-app/logs/gunicorn_supervisor.log
redirect_stderr = true

Start flask-app gunicorn:
sudo supervisorctl update
sudo supervisorctl status
You can use the following commands as well:
sudo supervisorctl start flask-app
sudo supervisorctl start all
sudo supervisorctl help|avail|stop|restart

Test that the application is running

Thursday, July 10, 2014

Insomnia due to back pain

I've noticed a number of people are posting on medical advice websites with the following symptoms: Sleep for 2-5 hours and wake up with a lot of back pain which goes away after getting up. Even napping during the day lying down will cause back pain in a couple of hours especially after a meal.

If this is happening to you, you may be suffering from acid-reflux erosion of the esophagus which can cause enervation (activation) of the nerves in the esophagus and stomach. This leads to your back pain via a process called Referred Pain. Referred pain is the process where pain induced in one part of your body is 'felt' in another part. As you can see from the chart in the Wikipedia article, stomach-based referred pain shows up in the middle of the back along the spine.

Now these pain symptoms are not going to be an exact match to the chart. Personally, I would feel like an electric charge was running along one of my ribs from my spine to my front during the earlier stages of my symptoms. Everybody's anatomy is slightly different and you'll get variations on the theme. However, it was primarily back pain that I was feeling. Now my pain almost exactly matches the chart.

After way too many specialists including a neurologist who should have had a clue about this, my GP at the time, Dr Karkalis in King of Prussia (fantastic doctor IMHO) who likes to review challenging patient charts at night for fun, thought my symptoms might be due to acid reflux. He was right, but in order to finalize the diagnosis, he prescribed a proton-pump inhibitor. After a few weeks my back pain from sleep was reduced significantly.

Another way to diagnose this and manage it longer term is to tilt the head of your bed up by 15-20 degrees to let gravity keep the acid in your stomach instead allowing it into your esophagus. If your back pain abates (not necessarily overnight though it often does) fairly quickly, then your back pain is likely due to acid reflux.

Sadly, you will need to sleep elevated for the rest of your life if you have acid-reflux back pain. The proton-pump inhibitors are pretty safe drugs, but they are not always be able to control your acid-reflux enough to control the pain completely. As you can see from my hammock blog post, hammocks work really well to set the right angle for sleeping and are much less expensive than adjustable beds.

Your acid reflux will be more or less severe at different times due to exercise, stress, eating habits, body weight so your management of it will need to accommodate the severity of your acid reflux. In other words, you may need to increase the angle of your bed when your acid reflux is more severe.

Also, check with your doctor and get tested for Barret's Esophagus. Basically, serious acid reflux sufferers are at higher risk for esophageal cancer.

Sunday, August 26, 2012

Acid Reflux, Camping, Hammocks and Holes

This is a personal blog article.  I generally try to keep this to professional matters, but I would like to record this for those of us suffering from acid reflux.  I've been dealing with it for over a decade now and mostly control it via mechanical means - sleeping on an incline.  After a couple of hours sleeping flat, I get referred pain from my esophagus which feels like back pain.  I try really hard to figure out how to sleep on an incline so I can get 6-8 hours of sleep instead of 2-3 hours of sleep and then 2-3 hours sitting up until the pain subsides, rinse, repeat.  

I was camping last weekend, first time since I've started noticing my acid reflux.  I generally suffer when away from home and try all sorts of tricks with setting the bed on blocks to create an incline, build a mound of pillows, or sleep in a recliner.  I wasn't looking forward to sleeping on the ground for a couple of nights.  

I tried to find a spot on a bit of a slope, but that had to be balanced with the desire to not slide down on a slippery tent floor in a slippery sleeping bag.  The first night was absolutely miserable.  I did manage 5 hours or so I think.  I woke up somewhere between 3-4am in pain and left the tent so I wouldn't disturb my campmates.  Being in pain, cold, and really tired doesn't make for a lovely camping trip.  

I was absolutely dreading the coming night and trying to find a nice spot of ground (shaped like a recliner) to set up my sleeping bag and pad and praying that it wouldn't rain.  My wife fortunately found the right spot and not something I would have thought of.  It was a hole about 2 feet deep, 2 feet wide and 3 feet long in a U shape.  It turned out to be a perfect, recliner-like, shape.  I tried it out and immediately felt comfortable.  Long story short, I had a great night sleeping in the hole.  I heartily recommend digging a hole to sleep in if you have trouble sleeping on your back or sleeping flat due to acid reflux issues.

This experience started me thinking about using a hammock when away from home as it would provide the same shape..  Looking on Google, there are a LOT of articles on using baby hammocks for babies with acid reflux and very few about adults using hammocks to manage acid reflux.  I took the plunge anyway and bought a hammock to try out.  I slept in it last night, and it worked great.  I was able to sleep for a very long time (about 10 hours - trying to catch up on missed sleep).  It was very comfortable all night, and I had no pain indicative of acid reflux this morning. 

It seems to be a successful experiment - though I do need a few more data points to fully confirm it of course.  Assuming that additional data points confirm this approach, I need to figure out how to take the hammock with me when traveling.  Hotels don't generally provide hammock hooks in the wall.  Travel-wise, hammocks don't take up much room which is good as I hate checking bags when I fly.  The hammock I tried out was the ENO Double Nest Hammock which doesn't take up much space or weight (about the size of a grapefruit and less than two pounds).

ENO Double Nest Hammock (Tomato/Khaki)

ENO Double Nest Hammock (Navy/Olive)

These straps are handy to hang the hammock with:  ENO Slap Straps

I'd recommend getting two carabiners to replace the ones that come with the hammock based on reviews I saw on Amazon:  Black Diamond Neutrino Carabiner - Grey