<commit_before>import Vue from 'vue'
import Vuex from 'vuex'
import FApp from './firebase'
import {vm} from '../main.js'

Vue.use(Vuex)

export const SAuth = new Vuex.Store({
  state: {
    userInitialized: false,
    user: null,
    memberProfile: null,
    redirectPath: ''
  },

  getters: {
    displayName(state) {
      let dn = 'Visitor'
      if (state.memberProfile && state.memberProfile.displayName)
        dn = state.memberProfile.displayName
      else if (state.user && state.user.phoneNumber)
        dn = `Member (${state.user.phoneNumber})`
      return dn
    }
  },

  mutations: {
    UPDATE_FIREBASE_USER(state, {user}) {
      console.log('User has been initialized ...')
      state.userInitialized = true
      if (user) {
        console.log('Good user')
        state.user = {
          uid: user.uid,
          displayName: user.phoneNumber,
          phoneNumber: user.phoneNumber
        }

        // Redirect ...
        if (state.redirectPath) {
          const path = state.redirectPath
          state.redirectPath = '' // clear the redirectPath right before redirecting
          vm.$router.replace(path)
        }
      } else {
        console.log('Empty user')
        state.user = null
      }
    },

    UPDATE_MEMBER_PROFILE(state, {member}) {
      state.memberProfile = member
    },

    ASK_TO_LOGIN(state, {redirectPath}) {
      if (state.user) {
        // Already logged-in
        state.redirectPath = ''
        return
      }

      state.redirectPath = redirectPath
    }
  }
})

let memberProfileRefURI = null

// Watch for changes on the Firebase Auth
FApp.auth().onAuthStateChanged((user) => {
  SAuth.commit('UPDATE_FIREBASE_USER', {user})

  if (memberProfileRefURI) {
    memberProfileRefURI.off()
    memberProfileRefURI = null
  }

  if (user) {
    memberProfileRefURI = FApp.database().ref(`/members/${user.uid}`)

    // Watch changes on the /members/$uid
    memberProfileRefURI.on('value', (snapshot) => {
      if (snapshot.exists()) {
        SAuth.commit('UPDATE_MEMBER_PROFILE', {member: snapshot.val()})
      } else {
        SAuth.commit('UPDATE_MEMBER_PROFILE', {member: null})
      }
    })
  }
  else {
    SAuth.commit('UPDATE_MEMBER_PROFILE', {member: null})
  }
})
<commit_msg>Set the member's phoneNumber attribute upon login.<commit_after>import Vue from 'vue'
import Vuex from 'vuex'
import FApp from './firebase'
import {vm} from '../main.js'

Vue.use(Vuex)

export const SAuth = new Vuex.Store({
  state: {
    userInitialized: false,
    user: null,
    memberProfile: null,
    redirectPath: ''
  },

  getters: {
    displayName(state) {
      let dn = 'Visitor'
      if (state.memberProfile && state.memberProfile.displayName)
        dn = state.memberProfile.displayName
      else if (state.user && state.user.phoneNumber)
        dn = `Member (${state.user.phoneNumber})`
      return dn
    }
  },

  mutations: {
    UPDATE_FIREBASE_USER(state, {user}) {
      console.log('User has been initialized ...')
      state.userInitialized = true
      if (user) {
        console.log('Good user')
        state.user = {
          uid: user.uid,
          displayName: user.phoneNumber,
          phoneNumber: user.phoneNumber
        }

        // Set the phone number to the members
        FApp.database().ref(`/members/${user.uid}/phoneNumber`).set(user.phoneNumber)

        // Redirect ...
        if (state.redirectPath) {
          const path = state.redirectPath
          state.redirectPath = '' // clear the redirectPath right before redirecting
          vm.$router.replace(path)
        }
      } else {
        console.log('Empty user')
        state.user = null
      }
    },

    UPDATE_MEMBER_PROFILE(state, {member}) {
      state.memberProfile = member
    },

    ASK_TO_LOGIN(state, {redirectPath}) {
      if (state.user) {
        // Already logged-in
        state.redirectPath = ''
        return
      }

      state.redirectPath = redirectPath
    }
  }
})

let memberProfileRefURI = null

// Watch for changes on the Firebase Auth
FApp.auth().onAuthStateChanged((user) => {
  SAuth.commit('UPDATE_FIREBASE_USER', {user})

  if (memberProfileRefURI) {
    memberProfileRefURI.off()
    memberProfileRefURI = null
  }

  if (user) {
    memberProfileRefURI = FApp.database().ref(`/members/${user.uid}`)

    // Watch changes on the /members/$uid
    memberProfileRefURI.on('value', (snapshot) => {
      if (snapshot.exists()) {
        SAuth.commit('UPDATE_MEMBER_PROFILE', {member: snapshot.val()})
      } else {
        SAuth.commit('UPDATE_MEMBER_PROFILE', {member: null})
      }
    })
  }
  else {
    SAuth.commit('UPDATE_MEMBER_PROFILE', {member: null})
  }
})
<|endoftext|>


<commit_before>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var serialPort = require('serialport');

app.get('/', function(req, res){
    res.sendFile(__dirname + '\\views\\index2.html');
});

var serial_connections = {};
var serial_connections_details = {};
var custom_connections = {};

io.on('connection', function(socket){

    socket.on('get ports', function
        () {
        console.log("Ports requested");
        serialPort.list(function (err, ports) {
            var o = [];
            for (var connection in ports) {
                if (ports[connection].comName in serial_connections) {
                    o.push({
                        comName: ports[connection].comName,
                        connected: 'Disconnect',
                        name: serial_connections_details[ports[connection].comName].name,
                        module: serial_connections_details[ports[connection].comName].module
                    });
                }
                else {
                    o.push({
                        comName: ports[connection].comName,
                        connected: 'Connect'
                    });
                }
            }
            socket.emit('port numbers', o);
        });
    });

    socket.on('Connect', function (port_name) {
        if(port_name==null || port_name ==''){
            socket.emit('error message', 'Error: No port selected');
            return console.log('Error: No port selected');
        }
        if (!(port_name in serial_connections)) {
            serial_connections_details[port_name] = {
                name: "default",
                module: "unknown"
            };
            serial_connections[port_name] = new serialPort(port_name,
                {baudRate: 115200, parser: serialPort.parsers.readline("\r\n")},
                function (err) {
                    if (err) {
                        socket.emit('error message', err.message);
                        return console.log('Error: ', err.message);
                    }
                    serial_connections[port_name].on('data', function (data) {
                        console.log(data);
                        if(data.length >=12) {
                            if (data.substr(0, 12) === "Module Type:") {
                                serial_connections_details[port_name].module = data.substr(13);
                                return;
                            }
                        }
                        socket.emit('data',
                            {
                                'comName': port_name,
                                'data': data,
                                'name': serial_connections_details[port_name].name,
                                'module': serial_connections_details[port_name].module
                            });
                    });

                    serial_connections[port_name].write('Hello', function (err) {
                        if (err) {
                            socket.emit('error message', err.message);
                            return console.log('Error on Write:', err.message);
                        }
                    });
                    /*
                    serial_connections[port_name].on('data', function (data) {

                        console.log(data);
                        socket.emit('data', data);
                        /*
                        if(serial_connections_details[port_name].name in custom_connections) {
                            for (var detail in serial_connections_details) {
                                if(detail.name == custom_connections[serial_connections_details[port_name].name]) {
                                    serial_connections[detail].write(data, function (err) {
                                        if (err) {
                                            socket.emit('error message', err.message);
                                            return console.log('Error on Write:', err.message);
                                        }
                                    });
                                    break;
                                }
                            }
                        } else {
                            console.log(data);
                            socket.emit('data', data);
                        }

                    });*/
                });
        }
    });

    socket.on('Disconnect', function (port_name) {
        if (!(port_name in serial_connections)){
            socket.emit('error message','Error: User Attempted to close port with no open connection');
            return console.log("Error: User Attempted to close port with no open connection")
        }
        serial_connections[port_name].close(function (err) {
            if(err) {
                socket.emit('error message', err.message);
                return console.log(err);
            }
        });
        delete serial_connections[port_name];
        socket.emit('closed', "Closed: " + port_name);
        console.log(Object.keys(serial_connections).length);

    });

    socket.on('send message', function (received_message) {
        console.log(received_message);
        if (!(received_message[0] in serial_connections)){
            socket.emit('error message','Error: User Attempted to write to port with no open connection');
            return console.log("Error: User Attempted to write to port with no open connection")}
        serial_connections[received_message[0]].write(received_message[1], function(err){
            if (err){return console.log(err)}
        });
    });

    socket.on('update name', function(data) {
        if (data[0] in serial_connections_details) {
            serial_connections_details[data[0]].name = data[1];
        }
    });

    socket.on('establish connection', function (data) {
        var flag = 0;
        for(var portName in serial_connections_details) {
            if (serial_connections_details[portName].name == data.source || serial_connections_details[portName].name == data.destination) {
                flag +=1;
            }
        }
        if(flag==2) {
            custom_connections[data.source] = data.destination;
        } else{
            socket.emit('error message', 'Error: One of the names is invalid');
        }
    });

});

http.listen(3000, function(){
    console.log('listening on *:3000');
});

<commit_msg>Input Redirection working as expected<commit_after>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var serialPort = require('serialport');

app.get('/', function(req, res){
    res.sendFile(__dirname + '\\views\\index2.html');
});

var serial_connections = {};
var serial_connections_details = {};
var custom_connections = {};

io.on('connection', function(socket){

    socket.on('get ports', function
        () {
        console.log("Ports requested");
        serialPort.list(function (err, ports) {
            var o = [];
            for (var connection in ports) {
                if (ports[connection].comName in serial_connections) {
                    o.push({
                        comName: ports[connection].comName,
                        connected: 'Disconnect',
                        name: serial_connections_details[ports[connection].comName].name,
                        module: serial_connections_details[ports[connection].comName].module
                    });
                }
                else {
                    o.push({
                        comName: ports[connection].comName,
                        connected: 'Connect'
                    });
                }
            }
            socket.emit('port numbers', o);
        });
    });

    socket.on('Connect', function (port_name) {
        if(port_name==null || port_name ==''){
            socket.emit('error message', 'Error: No port selected');
            return console.log('Error: No port selected');
        }
        if (!(port_name in serial_connections)) {
            serial_connections_details[port_name] = {
                name: "default",
                module: "unknown"
            };
            serial_connections[port_name] = new serialPort(port_name,
                {baudRate: 115200, parser: serialPort.parsers.readline("\r\n")},
                function (err) {
                    if (err) {
                        socket.emit('error message', err.message);
                        return console.log('Error: ', err.message);
                    }
                    serial_connections[port_name].on('data', function (data) {
                        console.log(data);

                        if(data.length >=12) {
                            if (data.substr(0, 12) === "Module Type:") {
                                serial_connections_details[port_name].module = data.substr(13);
                                return;
                            }
                        }

                        if(serial_connections_details[port_name].name in custom_connections) {
                            console.log("There exists a Connection");
                            console.log(custom_connections[serial_connections_details[port_name].name]);

                            for(var connection in serial_connections_details) {
                                console.log(connection);
                                if(serial_connections_details[connection].name === custom_connections[serial_connections_details[port_name].name]) {
                                    serial_connections[connection].write(data);
                                }
                            }
                        } else {
                            socket.emit('data',
                                {
                                    'comName': port_name,
                                    'data': data,
                                    'name': serial_connections_details[port_name].name,
                                    'module': serial_connections_details[port_name].module
                                });
                        }
                    });

                    serial_connections[port_name].write('Hello', function (err) {
                        if (err) {
                            socket.emit('error message', err.message);
                            return console.log('Error on Write:', err.message);
                        }
                    });
                });
        }
    });

    socket.on('Disconnect', function (port_name) {
        if (!(port_name in serial_connections)){
            socket.emit('error message','Error: User Attempted to close port with no open connection');
            return console.log("Error: User Attempted to close port with no open connection")
        }
        serial_connections[port_name].close(function (err) {
            if(err) {
                socket.emit('error message', err.message);
                return console.log(err);
            }
        });
        delete serial_connections[port_name];
        socket.emit('closed', "Closed: " + port_name);
        console.log(Object.keys(serial_connections).length);

    });

    socket.on('send message', function (received_message) {
        console.log(received_message);
        if (!(received_message[0] in serial_connections)){
            socket.emit('error message','Error: User Attempted to write to port with no open connection');
            return console.log("Error: User Attempted to write to port with no open connection")}
        serial_connections[received_message[0]].write(received_message[1], function(err){
            if (err){return console.log(err)}
        });
    });

    socket.on('update name', function(data) {
        if (data[0] in serial_connections_details) {
            serial_connections_details[data[0]].name = data[1];
        }
    });

    socket.on('establish connection', function (data) {
        var flag = 0;
        for(var portName in serial_connections_details) {
            if (serial_connections_details[portName].name == data.source || serial_connections_details[portName].name == data.destination) {
                flag +=1;
            }
        }
        if(flag==2) {
            custom_connections[data.source] = data.destination;
        } else{
            socket.emit('error message', 'Error: One of the names is invalid');
        }
    });

});

http.listen(3000, function(){
    console.log('listening on *:3000');
});

<|endoftext|>


<commit_before>import {is_map, is_array, is_set, is_string, is_func } from './helper';
import {string_iter} from './string-iter.js';

/*
    Substring using iterators. Expects the iterators refer to the same string.
 */
export function substring( /*string_iter*/ start, /*string_iter*/ end )
{
    if ( !start || !end ) { return ''; }
    if ( start.index < end.index )
        return start.str.substring( start.index, end.index );

    return '';
}

/*
    Scan a quoted chunk of text. Quotes will be whatever the initial character is when called.
    @param itr string iterator
    @param invalid an array of any characters that are invalid (not allowed in the quoted area)
*/
export function substring_quoted( itr, invalid = null )
{
    let quote = itr.value;
    if ( invalid !== null && !(invalid instanceof Array) ) invalid = [invalid];

    itr.next();
    let it = itr.clone();

    let esc = false;
    while ( !itr.end() )
    {
        if ( itr.value === '\\' ) { esc = !esc; }
        else if ( itr.value === quote && !esc ) { break; }
        else if ( invalid && invalid.includes( itr.value ) ) { return ''; }
        itr.next();
    }

    let sub = substring( it, itr );
    itr.next();
    return sub;
}

/*
    Goto the end of a string
*/
export function scan_to_end( it )
{
    while ( !it.end() ) { it.next(); }
}

function _pick_check( v )
{
    if ( is_string( v ) )
    {
        return (it) => it.value === v;
    }
    else if ( is_map( v ) || is_set( v ) )
    {
        return (it) => v.has( it.value );
    }
    else if ( is_array( v ) )
    {
        return (it) => v.includes( it.value );
    }
    else if ( is_func( v ) )
    {
        return (it) => v( it.value );
    }
    else if ( typeof v === 'object' )
    {
        return (it) => v.hasOwnProperty( it.value );
    }

    return (it) => true;
}

function _scan( it, test, cmp )
{
    let _t = _pick_check( test );
    while( !it.end() && (_t( it ) === cmp) ) { it.next(); }
}

/*
    Advance iterator until some character is found
*/
export function scan_to( it, find )
{
    _scan( it, find, false );
}

/*
    Advance iterator while some character is unseen
*/
export function scan_while( it, skip )
{
    _scan( it, skip, true );
}

/*

*/
export function substring_scan( it, scan, find )
{
    let i = it.clone();
    scan( it, find );

    return substring( i, it );
}

export function substring_scan_to( it, find )
{
    return substring_scan( it, scan_to, find );
}

export function substring_scan_while( it, find )
{
    return substring_scan( it, scan_while, find );
}

export function str_read( itr, count )
{
    count = Math.trunc( count );

    let s = '';
    if ( count > 0 )
    {
        while( !itr.done() && count-- )
        {
            s += itr.value;
        }
    }
    return s;
}<commit_msg>refactor: comments, remove repetition, more helper functions, use Validators<commit_after>import {get_has} from './util';
import {string_iter} from './string-iter';
import {Validator, ListValidator} from './validator';

/*
    Substring using iterators. Expects the iterators refer to the same string.
 */
export function substring( /*string_iter*/ start, /*string_iter*/ end )
{
    if ( !start || !end ) { return ''; }
    if ( start.index < end.index )
        return start.str.substring( start.index, end.index );

    return '';
}

/**
    Scan a quoted chunk of text. Quotes will be whatever the initial character is when called.
    @param {*} itr string iterator
    @param {*} invalid any characters that cause failure
*/
export function substring_quoted( itr, invalid = null )
{
    let quote = itr.value;
    let is_invalid = get_has( invalid, false );

    itr.next();
    let it = itr.clone();

    let esc = false;
    while ( !itr.end() )
    {
        if ( itr.value === '\\' ) { esc = !esc; }
        else if ( itr.value === quote && !esc ) { break; }
        else if ( is_invalid( itr.value ) ) { return ''; }
        itr.next();
    }

    let sub = substring( it, itr );
    itr.next();
    return sub;
}

/*
    Goto the end of a string
*/
export function scan_to_end( it )
{
    while ( !it.end() ) { it.next(); }
}

/**
 * Iterate while get-value( test ) === cmp
 * @param {*} it iterator
 * @param {*} test collection
 * @param {*} cmp comparison value
 */
function _scan( it, test, cmp )
{
    let _t = get_has( test );
    while( !it.done && (_t( it.value ) === cmp) )
    {
        it.next();
    }
}

/**
    Advance iterator until some character is found
*/
export function scan_to( it, pred )
{
    _scan( it, pred, false );
}

/**
    Advance iterator while some character is unseen
*/
export function scan_while( it, pred )
{
    _scan( it, pred, true );
}

/**
 * iterate using `scan` and `find`. return substring of span.
 * @param {*} it iterator
 * @param {*} scan function
 * @param {*} find comparison value / collection
 */
export function substring_scan( it, scan, find )
{
    let i = it.clone();
    scan( it, find );

    return substring( i, it );
}

/**
 * Iterate until `find` is met and return substring of span
 * @param {*} it iterator
 * @param {*} find comparison value/collection
 */
export function substring_scan_to( it, find )
{
    return substring_scan( it, scan_to, find );
}

/**
 * Iterate while `find` is met and return substring of span
 * @param {*} it iterator
 * @param {*} find comparison value/collection
 */
export function substring_scan_while( it, find )
{
    return substring_scan( it, scan_while, find );
}

/**
 * Get a string of `count` characters
 * @param {*} itr
 * @param {*} count number of characters to read
 */
export function str_read( itr, count )
{
    count = Math.trunc( count );

    let s = '';
    if ( count > 0 )
    {
        while( !itr.done() && count-- )
        {
            s += itr.value;
        }
    }
    return s;
}

/**
 * Scan a string using a validator. return substring of span
 * @param {*} itr
 * @param {*} validator Validator type
 */
export function substring_validator( itr, validator = new Validator() )
{
    let it = itr.clone();
    scan_while( itr, validator );

    return substring( it, itr );
}

export function substring_identifier( itr, validator = new IdentfierValidator() )
{
    return substring_validator( itr, validator ).toLowerCase();
}

export let whitespace_validator = new ListValidator( [
            '\u0009', '\u000A', '\u000B', '\u000C', '\u000D', '\u0020', '\u0085', '\u00A0',
            '\u1680', '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006',
            '\u2007', '\u2008', '\u2009', '\u200A', '\u2028', '\u2029', '\u202F', '\u205F',
            '\u3000' ] );

export function skip_whitespace( itr )
{
    scan_while( itr, whitespace_validator );
}

export function find_whitespace( itr )
{
    scan_to( itr, whitespace_validator );
}<|endoftext|>


<commit_before>'use strict';
console.log("Heyyyy");
var userName = prompt('Hello there!  Whom do we have the pleasure of talking with today?');

alert('It\'s a pleasure to meet you ' + userName + ', We\'re going play a quick game and see what you can tell about me with some good ol intuition.');

var scoreKeeper = 0;

var veteran = prompt('Did I serve in the Armed Forces?');
console.log('Veteran?', veteran);

 if( veteran.toLowerCase() == 'yes') {
  alert('See off to a good start already!  I was in the Army for 6 years.');
  scoreKeeper++;

 } else {
  alert('Ooops!  Maybe you\'ll get the next one');
 }

var food = prompt('Would you believe my favorite fruit is watermelon?');
console.log('love watermelon', food);

  if(food.toLowerCase() == 'yes') {
    alert('Of course right?!  How could anyone not love watermelon!  Look at you go with the 2 piece ^_^ .');
    scoreKeeper++;

  } else {
    alert('Actually I am pretty crazy about watermelon!  I once ate two large watermelons in one sitting...it was not the best idea but it was delicious!');
  }

var home = prompt('Do I live in Seattle?');
console.log('live in Seattle?', home);

  if(home.toLowerCase() == 'no') {
    alert('Correct!  Too expensive!');
    scoreKeeper++;

} else{
    alert('Nah, I actually live across the Puget Sound');
  }

var wine = prompt('Am I a fan of wine?');
console.log('wine', wine);

 if(wine.toLowerCase() == 'yes') {
    alert('YES!  I love wine! mmmm');

  }else {
    alert('Actually I am a wine-o, haha');
  }

var age = prompt('Am I in my 30\'s?');
console.log('30s', age);

  if(age.toLowerCase() == 'yes') {
    alert('yeahhh I am becoming old');

  } else {
    alert('awww thank you, unfortunely I am getting old');
  }

var myVehicle = 3;
var guess;
var answer = true
for (var attempts = 4; attempts > 0 && answer; attempts--) {
  guess = prompt('How many vehicles do you think I own including motorcyles?');
  guess = parseInt(guess);

  if(guess === myVehicle) {
    alert('Correct!');
    answer = false
  } else if (attempts === 1){
    alert('Sorry you are out of chances');
  } else if(guess < 3){
    alert('Not quite, too low');
  } else {
    alert('Whoa! I am not made of money, try a lower number');
  }
}

var answer = true;
var guess;
var countries = ['test1','test2'];
var i;
var secondaryCon = true;

for(var attempts = 6; attempts > 0 && answer; attempts--) {
        guess = prompt('Can you name another country I have been to?');
        console.log('out of for loop' + attempts);

          for( i = 0; i < countries.length && secondaryCon; i++){
console.log('inner for loop' + i);
              if(guess === countries[i]) {
                  answer = false;
                  secondaryCon = false;
                  alert('Yes!  That\'s one of the answers, I would have also accepted: ' + countries + '.');
                  console.log('innerif ' + answer);

            } else if(i === countries.length -1) {
            alert('Unfortunely you are out of attempts.  Possible answers included: ' + countries + '.  Better luck next time!');
            console.log('inner elseif' + i);

        }

  }
}

alert('Well this concludes our little game!  I do hope you enjoyed yourself.  You answered ' + scoreKeeper + ' out of 7 correctly!')
<commit_msg>finished up the questions with a score tracker.  added alert msg at end letting user know how many questions were answered correctly<commit_after>'use strict';
console.log("Heyyyy");
var userName = prompt('Hello there!  Whom do we have the pleasure of talking with today?');

alert('It\'s a pleasure to meet you ' + userName + ', We\'re going play a quick game and see what you can tell about me with some good ol intuition.');

var scoreKeeper = 0;

var veteran = prompt('Did I serve in the Armed Forces?');
console.log('Veteran?', veteran);

if( veteran.toLowerCase() == 'yes') {
  alert('See off to a good start already!  I was in the Army for 6 years.');
  scoreKeeper++;

} else {
  alert('Ooops!  Maybe you\'ll get the next one');
}

var food = prompt('Would you believe my favorite fruit is watermelon?');
console.log('love watermelon', food);

if(food.toLowerCase() == 'yes') {
  alert('Of course right?!  How could anyone not love watermelon!  Look at you go with the 2 piece ^_^ .');
  scoreKeeper++;

} else {
  alert('Actually I am pretty crazy about watermelon!  I once ate two large watermelons in one sitting...it was not the best idea but it was delicious!');
}

var home = prompt('Do I live in Seattle?');
console.log('live in Seattle?', home);

if(home.toLowerCase() == 'no') {
  alert('Correct!  Too expensive!');
  scoreKeeper++;

} else{
  alert('Nah, I actually live across the Puget Sound');
}

var wine = prompt('Am I a fan of wine?');
console.log('wine', wine);

if(wine.toLowerCase() == 'yes') {
  alert('YES!  I love wine! mmmm');
  scoreKeeper++;

}else {
  alert('Actually I am a wine-o, haha');
}

var age = prompt('Am I in my 30\'s?');
console.log('30s', age);

if(age.toLowerCase() == 'yes') {
  alert('yeahhh I am becoming old');
  scoreKeeper++;

} else {
  alert('awww thank you, unfortunely I am getting old');
}

var myVehicle = 3;
var guess;
var answer = true
for (var attempts = 4; attempts > 0 && answer; attempts--) {
  guess = prompt('How many vehicles do you think I own including motorcyles?');
  guess = parseInt(guess);

  if(guess === myVehicle) {
    alert('Correct! I have 1 car and 2 motorcyles');
    answer = false;
    scoreKeeper++;
  } else if (attempts === 1){
    alert('Sorry you are out of chances');
  } else if(guess < 3){
    alert('Not quite, too low');
  } else {
    alert('Whoa! I am not made of money, try a lower number');
  }
}

var answer = true;
var guess;
var countries = ['Iraq','Afghanistan','Kuwait','Pakistan','Iceland','Germany','Ireland','Netherlands','Scotland','Mexico','Canada','Kazakhstan','Korea','Japan'];
var i;
var secondaryCon = true;

for(var attempts = 6; attempts > 0 && answer; attempts--) {
  guess = prompt('Can you name another country I have been to?');
  console.log('out of for loop' + attempts);

  for( i = 0; i < countries.length && secondaryCon; i++){
    console.log('inner for loop' + i);
    if(guess === countries[i]) {
      answer = false;
      secondaryCon = false;
      alert('Yes!  That\'s one of the answers, I would have also accepted: ' + countries + '.');
      console.log('innerif ' + answer);
      scoreKeeper++;

    } else if(i === countries.length -1) {
      alert('Unfortunely you are out of attempts.  Possible answers included: ' + countries + '.  Better luck next time!');
      console.log('inner elseif' + i);

    } else {
      alert('Ooo, nice try.  I actually have not been there before, but now that you mention it maybe I will take a trip!');
    }

  }
}

alert('Well this concludes our little game!  I do hope you enjoyed yourself.  You answered ' + scoreKeeper + ' out of 7 correctly!')
<|endoftext|>


<commit_before>var fs = require('fs')
var path = require('path')
var util = require('util')
var mqtt = require('mqtt');
var express = require('express')
var morgan = require('morgan')
var bodyParser = require('body-parser')
var parameterize = require('parameterize');

var config = require('./config/config.json');

var harmonyHubDiscover = require('harmonyhubjs-discover')
var harmony = require('harmonyhubjs-client')

var harmonyHubClient
var harmonyActivitiesCache = {}
var harmonyActivityUpdateInterval = 1*60*1000 // 1 minute
var harmonyActivityUpdateTimer

var harmonyState
var harmonyStateUpdateInterval = 5*1000 // 5 seconds
var harmonyStateUpdateTimer

var mqttClient = mqtt.connect(config.mqtt_host);
var TOPIC_NAMESPACE = "harmony-api"

var app = express()
app.use(bodyParser.urlencoded({ extended: false }))
app.use(express.static(path.join(__dirname, 'public')));

var logFormat = "'[:date[iso]] - :remote-addr - :method :url :status :response-time ms - :res[content-length]b'"
app.use(morgan(logFormat))

// Middleware
// Check to make sure we have a harmonyHubClient to connect to
var hasHarmonyHubClient = function(req, res, next) {
  if (hasHarmonyHubClient) {
    next()
  }else{
    res.status(500).json({message: "Can not connect to hub."})
  }
}
app.use(hasHarmonyHubClient)

var discover = new harmonyHubDiscover(61991)

discover.on('online', function(hubInfo) {
  // Triggered when a new hub was found
  console.log('Hub discovered ' + hubInfo.ip + '.')

  if (hubInfo.ip) {
    console.log('Stopping discovery.')
    discover.stop()

    harmony(hubInfo.ip).then(startProcessing)
  }

})

if (config['hub_ip']) {
  // Connect to hub:
  console.log('Connecting to Harmony hub at ' + config['hub_ip'])
  harmony(config['hub_ip']).then(startProcessing)
}else{
  // Look for hubs:
  console.log('Starting discovery.')
  discover.start()
}

// mqtt api

mqttClient.on('connect', function () {
  mqttClient.subscribe(TOPIC_NAMESPACE + '/activities/+/command')
});

mqttClient.on('message', function (topic, message) {
  var commandPattern = new RegExp(/activities\/(.*)\/command/);
  var commandMatches = topic.match(commandPattern);

  if (commandMatches) {
    var activitySlug = commandMatches[1]
    var state = message.toString()

    activity = activityBySlug(activitySlug)
    if (!activity) { return }

    if (state === 'on') {
      startActivity(activity.id)
    }else if (state === 'off'){
      off()
    }
  }

});

function startProcessing(harmonyClient){
  harmonyHubClient = harmonyClient

  // update the list of activities
  updateActivities()
  // then do it on the set interval
  clearInterval(harmonyActivityUpdateTimer)
  harmonyActivityUpdateTimer = setInterval(function(){ updateActivities() }, harmonyActivityUpdateInterval)

  // update the list of activities on the set interval
  clearInterval(harmonyStateUpdateTimer)
  harmonyStateUpdateTimer = setInterval(function(){ updateState() }, harmonyStateUpdateInterval)
}

function updateActivities(){
  if (!harmonyHubClient) { return }
  console.log('Updating activities.')

  harmonyHubClient.getActivities().then(function(activities){
    foundActivities = {}
    activities.some(function(activity) {
      foundActivities[activity.id] = {id: activity.id, slug: parameterize(activity.label).replace(/-/g, '_'), label:activity.label, isAVActivity: activity.isAVActivity}
    })

    harmonyActivitiesCache = foundActivities
  })
}

function updateState(){
  if (!harmonyHubClient) { return }
  console.log('Updating state.')

  // save for comparing later after we get the true current state
  var previousActivity = currentActivity()

  harmonyHubClient.getCurrentActivity().then(function(activityId){
    data = {off: true}

    activity = harmonyActivitiesCache[activityId]

    if (activityId != -1 && activity) {
      data = {off: false, current_activity: activity}
    }else{
      data = {off: true, current_activity: activity}
    }

    // cache state for later
    harmonyState = data

    if (!previousActivity || (activity.id != previousActivity.id)) {
      publish('current_activity', activity.slug, {retain: true})
      publish('state', activity.id == -1 ? 'off' : 'on' , {retain: true})

      for (var i = 0; i < cachedHarmonyActivities().length; i++) {
        activities = cachedHarmonyActivities()
        cachedActivity = activities[i]

        if (activity == cachedActivity) {
          publish('activities/' + cachedActivity.slug + '/state', 'on', {retain: true})
        }else{
          publish('activities/' + cachedActivity.slug + '/state', 'off', {retain: true})
        }
      }
    }

  })
}

function cachedHarmonyActivities(){
  return Object.keys(harmonyActivitiesCache).map(function(key) {
    return harmonyActivitiesCache[key]
  })
}

function currentActivity(){
  if (!harmonyHubClient || !harmonyState) { return null}

  return harmonyState.current_activity
}

function activityByName(activityName){
  var activity
  cachedHarmonyActivities().some(function(a) {
    if(a.label === activityName) {
      activity = a
      return true
    }
  })

  return activity
}

function activityBySlug(activitySlug){
  var activity
  cachedHarmonyActivities().some(function(a) {
    if(a.slug === activitySlug) {
      activity = a
      return true
    }
  })

  return activity
}

function off(){
  if (!harmonyHubClient) { return }

  harmonyHubClient.turnOff().then(function(){
    updateState()
  })
}

function startActivity(activityId){
  if (!harmonyHubClient) { return }

  harmonyHubClient.startActivity(activityId).then(function(){
    updateState()
  })
}

function publish(topic, message, options){
  topic = TOPIC_NAMESPACE + "/" + topic
  mqttClient.publish(topic, message, options);
}

app.get('/_ping', function(req, res){
  res.send('OK');
})

app.get('/', function(req, res){
  res.sendfile('index.html');
})

app.get('/activities', function(req, res){
  res.json({activities: cachedHarmonyActivities()})
})

app.get('/status', function(req, res){
  res.json(harmonyState)
})

app.put('/off', function(req, res){
  off()

  res.json({message: "ok"})
})

app.post('/start_activity', function(req, res){
  activity = activityBySlug(req.body.activity)

  if (activity) {
    startActivity(activity.id)

    res.json({message: "ok"})
  }else{
    res.status(404).json({message: "Not Found"})
  }
})

app.listen(process.env.PORT || 8282)
<commit_msg>kill this<commit_after>var fs = require('fs')
var path = require('path')
var util = require('util')
var mqtt = require('mqtt');
var express = require('express')
var morgan = require('morgan')
var bodyParser = require('body-parser')
var parameterize = require('parameterize');

var config = require('./config/config.json');

var harmonyHubDiscover = require('harmonyhubjs-discover')
var harmony = require('harmonyhubjs-client')

var harmonyHubClient
var harmonyActivitiesCache = {}
var harmonyActivityUpdateInterval = 1*60*1000 // 1 minute
var harmonyActivityUpdateTimer

var harmonyState
var harmonyStateUpdateInterval = 5*1000 // 5 seconds
var harmonyStateUpdateTimer

var mqttClient = mqtt.connect(config.mqtt_host);
var TOPIC_NAMESPACE = "harmony-api"

var app = express()
app.use(bodyParser.urlencoded({ extended: false }))
app.use(express.static(path.join(__dirname, 'public')));

var logFormat = "'[:date[iso]] - :remote-addr - :method :url :status :response-time ms - :res[content-length]b'"
app.use(morgan(logFormat))

// Middleware
// Check to make sure we have a harmonyHubClient to connect to
var hasHarmonyHubClient = function(req, res, next) {
  if (hasHarmonyHubClient) {
    next()
  }else{
    res.status(500).json({message: "Can not connect to hub."})
  }
}
app.use(hasHarmonyHubClient)

var discover = new harmonyHubDiscover(61991)

discover.on('online', function(hubInfo) {
  // Triggered when a new hub was found
  console.log('Hub discovered ' + hubInfo.ip + '.')

  if (hubInfo.ip) {
    console.log('Stopping discovery.')
    discover.stop()

    harmony(hubInfo.ip).then(startProcessing)
  }

})

if (config['hub_ip']) {
  // Connect to hub:
  console.log('Connecting to Harmony hub at ' + config['hub_ip'])
  harmony(config['hub_ip']).then(startProcessing)
}else{
  // Look for hubs:
  console.log('Starting discovery.')
  discover.start()
}

// mqtt api

mqttClient.on('connect', function () {
  mqttClient.subscribe(TOPIC_NAMESPACE + '/activities/+/command')
});

mqttClient.on('message', function (topic, message) {
  var commandPattern = new RegExp(/activities\/(.*)\/command/);
  var commandMatches = topic.match(commandPattern);

  if (commandMatches) {
    var activitySlug = commandMatches[1]
    var state = message.toString()

    activity = activityBySlug(activitySlug)
    if (!activity) { return }

    if (state === 'on') {
      startActivity(activity.id)
    }else if (state === 'off'){
      off()
    }
  }

});

function startProcessing(harmonyClient){
  harmonyHubClient = harmonyClient

  // update the list of activities
  updateActivities()
  // then do it on the set interval
  clearInterval(harmonyActivityUpdateTimer)
  harmonyActivityUpdateTimer = setInterval(function(){ updateActivities() }, harmonyActivityUpdateInterval)

  // update the list of activities on the set interval
  clearInterval(harmonyStateUpdateTimer)
  harmonyStateUpdateTimer = setInterval(function(){ updateState() }, harmonyStateUpdateInterval)
}

function updateActivities(){
  if (!harmonyHubClient) { return }
  console.log('Updating activities.')

  harmonyHubClient.getActivities().then(function(activities){
    foundActivities = {}
    activities.some(function(activity) {
      foundActivities[activity.id] = {id: activity.id, slug: parameterize(activity.label).replace(/-/g, '_'), label:activity.label, isAVActivity: activity.isAVActivity}
    })

    harmonyActivitiesCache = foundActivities
  })
}

function updateState(){
  if (!harmonyHubClient) { return }
  console.log('Updating state.')

  // save for comparing later after we get the true current state
  var previousActivity = currentActivity()

  harmonyHubClient.getCurrentActivity().then(function(activityId){
    data = {off: true}

    activity = harmonyActivitiesCache[activityId]

    if (activityId != -1 && activity) {
      data = {off: false, current_activity: activity}
    }else{
      data = {off: true, current_activity: activity}
    }

    // cache state for later
    harmonyState = data

    if (!previousActivity || (activity.id != previousActivity.id)) {
      publish('current_activity', activity.slug, {retain: true})
      publish('state', activity.id == -1 ? 'off' : 'on' , {retain: true})

      for (var i = 0; i < cachedHarmonyActivities().length; i++) {
        activities = cachedHarmonyActivities()
        cachedActivity = activities[i]

        if (activity == cachedActivity) {
          publish('activities/' + cachedActivity.slug + '/state', 'on', {retain: true})
        }else{
          publish('activities/' + cachedActivity.slug + '/state', 'off', {retain: true})
        }
      }
    }

  })
}

function cachedHarmonyActivities(){
  return Object.keys(harmonyActivitiesCache).map(function(key) {
    return harmonyActivitiesCache[key]
  })
}

function currentActivity(){
  if (!harmonyHubClient || !harmonyState) { return null}

  return harmonyState.current_activity
}

function activityBySlug(activitySlug){
  var activity
  cachedHarmonyActivities().some(function(a) {
    if(a.slug === activitySlug) {
      activity = a
      return true
    }
  })

  return activity
}

function off(){
  if (!harmonyHubClient) { return }

  harmonyHubClient.turnOff().then(function(){
    updateState()
  })
}

function startActivity(activityId){
  if (!harmonyHubClient) { return }

  harmonyHubClient.startActivity(activityId).then(function(){
    updateState()
  })
}

function publish(topic, message, options){
  topic = TOPIC_NAMESPACE + "/" + topic
  mqttClient.publish(topic, message, options);
}

app.get('/_ping', function(req, res){
  res.send('OK');
})

app.get('/', function(req, res){
  res.sendfile('index.html');
})

app.get('/activities', function(req, res){
  res.json({activities: cachedHarmonyActivities()})
})

app.get('/status', function(req, res){
  res.json(harmonyState)
})

app.put('/off', function(req, res){
  off()

  res.json({message: "ok"})
})

app.post('/start_activity', function(req, res){
  activity = activityBySlug(req.body.activity)

  if (activity) {
    startActivity(activity.id)

    res.json({message: "ok"})
  }else{
    res.status(404).json({message: "Not Found"})
  }
})

app.listen(process.env.PORT || 8282)
<|endoftext|>


<commit_before>/*jslint node:true*/

var _     = require('util').format,
	mysql = require('mysql2'),
	__    = function (foo) {
		// Extract string from function comment.
		// Check function youself before call to here.
		return foo.toString ().match(/\{\s*\/\*\s*([\s\S]*?)\s*\*\/\s*\}/)[1];
	};

var modDB = function (conf, mod) {
	var that = this;

	this.conf = conf.mysql;
	this.mod  = mod;
	this._  =  _; // sprintf like.
	this.__ = __; // extract string comment (multiline) from function.

	var authData = conf.mysql.auth;
	authData.multipleStatements = true;
	this.db   = mysql.createConnection (authData);
	var __errorHandler = function (err) {
		mod.log.error ('MySQL throw an error:', err.code, '; try to re-connect ...');

		that.db.query = function () { return false; };

		setTimeout(function () {
			that.db = mysql.createConnection (authData);
			that.db.on ('error', __errorHandler);
		}, 5000);
	};
	this.db.on ('error', __errorHandler);

	this.db.query (_('create database if not exists `%s` DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci; use `%s`;',
						conf.mysql.database, conf.mysql.database));
};

module.exports = function (conf, mod) {
	return new modDB (conf, mod);
};<commit_msg>small change of syntax<commit_after>/*jslint node:true*/

var _     = require('util').format,
	mysql = require('mysql2'),
	__    = function (foo) {
		// Extract string from function comment.
		// Check function youself before call to here.
		return foo.toString ().match(/\{\s*\/\*\s*([\s\S]*?)\s*\*\/\s*\}/)[1];
	};

var modDB = function (conf, mod) {
	var that = this;

	this.conf = conf.mysql;
	this.mod  = mod;
	this._  =  _; // sprintf like.
	this.__ = __; // extract string comment (multiline) from function.

	var authData = conf.mysql.auth;
	authData.multipleStatements = true;
	this.db   = mysql.createConnection (authData);
	var __errorHandler = function (err) {
		mod.log.error ('MySQL throw an error:', err.code, '; try to re-connect ...');

		that.db.query = function () { return false; };

		setTimeout(function () {
			that.db = mysql.createConnection (authData);
			that.db.on ('error', __errorHandler);
		}, 5000);
	};
	this.db.on ('error', __errorHandler);

	this.db.query (_('create database if not exists `%s` DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci; use `%s`;', conf.mysql.database, conf.mysql.database));
};

module.exports = function (conf, mod) {
	return new modDB (conf, mod);
};<|endoftext|>


<commit_before>import _ from 'underscore';
import React from 'react';
import FixedDataTable from 'fixed-data-table';
import TableHeader from './table_header';
import TableJawboneFilter from './table_jawbone_filter';
import $ from 'jquery';
const debug = require('debug')('bilprospekt-ui:table');

const {Table, Column, Cell} = FixedDataTable;

import {HeaderCell, NormalCell, SelectorCell} from './cells';
import ColumnWidthHelper from './helpers/column_width_helper.js';

const columnWidthHelper = new ColumnWidthHelper(1, []);
const selectorColumnWidth = 47;

const TableHolderComponent = React.createClass({
    propTypes: {
        //The data for the rows
        data: React.PropTypes.array.isRequired,

        //The current columns that should be rendered.
        columns: React.PropTypes.array.isRequired,

        //All the filters for the columns. Indexed by column key.
        columnFilters: React.PropTypes.object,

        //The current selected filters
        currentFilters: React.PropTypes.array,

        //All the columns that the user can pick between.
        allColumnsThatCouldBeRendered: React.PropTypes.array,
        onColumnChange: React.PropTypes.func,

        //Width and height of table
        width: React.PropTypes.oneOfType([
            React.PropTypes.oneOf(['auto']),
            React.PropTypes.number,
        ]),

        //Max height of table
        height: React.PropTypes.number,

        //Current sort value
        sort: React.PropTypes.shape({
            direction: React.PropTypes.string.isRequired,
            column: React.PropTypes.oneOfType([
                React.PropTypes.string,
                React.PropTypes.number,
            ]).isRequired,
        }),

        showLoadingComponent: React.PropTypes.bool,

        rowHeight: React.PropTypes.number,
        headerHeight: React.PropTypes.number,
        headerLabel: React.PropTypes.node,

        //If we should have a checkbox for rows.
        makeRowsSelectable: React.PropTypes.bool,
        //What rows are selected if we have makeRowsSelectable.
        selectedRows: React.PropTypes.array,
        //On a selection if we have makeRowsSelectable.
        onSelection: React.PropTypes.func,

        //Search hint
        searchHint: React.PropTypes.string,
        //If we want or don't want search
        useSearch: React.PropTypes.bool,

        //Trigger functions that haven't already been listed.
        onSearch: React.PropTypes.func,
        onFilter: React.PropTypes.func,
        onSort: React.PropTypes.func,
        onReachedBottom: React.PropTypes.func,
    },
    getDefaultProps() {
        return {
            data: [],
            columns: [],
            columnFilters: {},
            allColumnsThatCouldBeRendered: [],
            makeRowsSelectable: false,

            //Change these to what we'll probably use in prod.
            width: 'auto',
            height: 500,
            rowHeight: 46,
            headerHeight: 50,
            showLoadingComponent: false,
            useSearch: true,
            searchHint: '',
        };
    },
    getInitialState() {
        return {
            showJawbone: false,
        };
    },
    componentDidMount() {
        columnWidthHelper.onChange(() => this.forceUpdate());
        if (this.props.width === 'auto') {
            this._setDynamicWidthOnTable();
            $(window).on('resize', this._setDynamicWidthOnTable);
        } else {
            columnWidthHelper.setTotalWidth(this.props.width);
        }
    },
    _setDynamicWidthOnTable() {
        let width = $(this._holder).width();
        if (this.props.makeRowsSelectable) {
            width -= selectorColumnWidth;
        }
        columnWidthHelper.setTotalWidth(width);
    },
    componentWillUnmount() {
        $(window).off('resize', this._setDynamicWidthOnTable);
        columnWidthHelper.destroyListeners();
    },
    componentWillMount() {
       columnWidthHelper.setIdentifiers(_(this.props.columns).pluck('val'));
    },
    componentWillReceiveProps(nextProps, nextState) {
        if (nextProps.columns.length !== this.props.columns.length) {
            columnWidthHelper.setIdentifiers(_(nextProps.columns).pluck('val'));
        }
    },
    _onColumnResize(newWidth, col) {
        columnWidthHelper.setWidthForIdentifier(col, newWidth);
    },
    _onSearchChange(val) {
        if (typeof this.props.onSearch === 'function') {
            this.props.onSearch(val);
        }
    },
    _onSort(payload) {
        if (typeof this.props.onSort === 'function') {
            this.props.onSort(payload);
        }
    },
    _onColumnChange(newColumns) {
        if (typeof this.props.onColumnChange === 'function') {
            this.props.onColumnChange(newColumns);
        }
    },
    _onScrollEnd(x, y) {
        //onReachedBottom not a function, no need to do anything here then.
        if (typeof this.props.onReachedBottom !== 'function') return;

        const {rowHeight, data, height} = this.props;
        var triggerLimit = rowHeight * 20;
        var totalTableHeight = rowHeight * data.length - height;
        if (y > (totalTableHeight - triggerLimit)) {
            this.props.onReachedBottom();
        }
    },
    _onColumnHover({col}, state) {
        const {columnWidths} = columnWidthHelper.getState();
        const oldWidth = columnWidths[col];
        const newWidth = (state) ? oldWidth + 20 : oldWidth - 20;
        columnWidthHelper.setWidthForIdentifier(col, newWidth);
    },
    _showJawboneFilter() {
        this.setState({ showJawbone: !this.state.showJawbone });
    },
    _onChipRemove(key, val) {
        if (typeof this.props.onFilter === 'function') {
            this.props.onFilter([key, val]);
        }
    },
    render() {
        const data = this.props.data;
        const columnsToRender = this.props.columns;

        const {columnWidths, totalWidth} = columnWidthHelper.getState();
        debug('Column widths are', columnWidths, 'Total width', totalWidth);

        let cols = _(columnsToRender).map((col, index) => {
            const columnWidth = columnWidths[col.val];
            //Last element is not resizable
            const isResizable = (index === columnsToRender.length - 1) ? false : true;
            return (
                <Column
                    columnKey={col.val}
                    key={col.val}
                    {...columnWidth}
                    header={(props) => {
                        const filters = this.props.columnFilters[col.val];
                        const sort = (this.props.sort && this.props.sort.column === col.val)
                                  ? this.props.sort
                                  : null;

                        return <HeaderCell
                            onFilter={this.props.onFilter}
                            sort={sort}
                            onSort={this._onSort}
                            availableFilters={filters}
                            currentFilters={this.props.currentFilters}
                            {...col}
                            {...props} />
                    }}
                    cell={<NormalCell data={data} col={col.val} />}
                    isResizable={isResizable}
                />
            );
        });

        const props = this.props;
        if (props.makeRowsSelectable) {
            const key = 'BP-selector';
            cols.unshift(
                <Column
                    columnKey={key}
                    key={key}
                    isResizable={false}
                    width={selectorColumnWidth}
                    cell={<SelectorCell data={data} onChange={props.onSelection} selections={props.selectedRows} />}
                />
            )
        }

        const loadingComponent = props.showLoadingComponent
                  ? <LoadingComponent />
                  : null;

        //50 Is HeaderHeight. We want table to be same size as content. Or max height given by props.height
        const tableHeight = Math.min(50 + Math.max(props.data.length, 1) * props.rowHeight, props.height)
        return (

 this._holder = ref} style={{position: 'relative'}} className='bui-table-holder'>
                <TableHeader
                    onColumnChange={this._onColumnChange}
                    onSearchChange={this._onSearchChange}
                    allColumnsThatCouldBeRendered={props.allColumnsThatCouldBeRendered}
                    currentColumns={columnsToRender}
                    currentFilters={this.props.currentFilters}
                    justifyColumns={columnWidthHelper.justifyColumns.bind(columnWidthHelper)}
                    headerLabel={this.props.headerLabel}
                    showJawboneFilter={this._showJawboneFilter}
                    selections={props.selectedRows}
                    onFilter={this.props.onFilter}
                    searchHint={this.props.searchHint}
                    useSearch={this.props.useSearch}
                />
                <TableJawboneFilter columns={this.props.allColumnsThatCouldBeRendered}
                    onChipRemove={this._onChipRemove}
                    currentFilters={this.props.currentFilters}
                    columnFilters={this.props.columnFilters}

                    visible={this.state.showJawbone} />

                {cols}

                {loadingComponent}

        );
    }
});

const LoadingComponent = React.createClass({
    propTypes: {
        loadingText: React.PropTypes.string,
    },
    getDefaultProps() {
        return {
            loadingText: 'Laddar in fler resultat...',
        };
    },
    render() {
        const loadingStyle = {
            position: 'absolute',
            bottom: 0,
            width: '100%',
            textAlign: 'center',
            paddingTop: 6,
            backgroundColor: 'rgba(255, 255, 255, 0.9)',
            height: 35,
            fontSize: 14,
        };

        const textStyle = {
            paddingLeft: 5,
        };

        return (

                {this.props.loadingText}

        )
    }
});

export default TableHolderComponent;
<commit_msg>changed loader for table<commit_after>import _ from 'underscore';
import React from 'react';
import FixedDataTable from 'fixed-data-table';
import TableHeader from './table_header';
import TableJawboneFilter from './table_jawbone_filter';
import $ from 'jquery';
const debug = require('debug')('bilprospekt-ui:table');

import Loader from '../loader';

const {Table, Column, Cell} = FixedDataTable;

import {HeaderCell, NormalCell, SelectorCell} from './cells';
import ColumnWidthHelper from './helpers/column_width_helper.js';

const columnWidthHelper = new ColumnWidthHelper(1, []);
const selectorColumnWidth = 47;

const TableHolderComponent = React.createClass({
    propTypes: {
        //The data for the rows
        data: React.PropTypes.array.isRequired,

        //The current columns that should be rendered.
        columns: React.PropTypes.array.isRequired,

        //All the filters for the columns. Indexed by column key.
        columnFilters: React.PropTypes.object,

        //The current selected filters
        currentFilters: React.PropTypes.array,

        //All the columns that the user can pick between.
        allColumnsThatCouldBeRendered: React.PropTypes.array,
        onColumnChange: React.PropTypes.func,

        //Width and height of table
        width: React.PropTypes.oneOfType([
            React.PropTypes.oneOf(['auto']),
            React.PropTypes.number,
        ]),

        //Max height of table
        height: React.PropTypes.number,

        //Current sort value
        sort: React.PropTypes.shape({
            direction: React.PropTypes.string.isRequired,
            column: React.PropTypes.oneOfType([
                React.PropTypes.string,
                React.PropTypes.number,
            ]).isRequired,
        }),

        showLoadingComponent: React.PropTypes.bool,

        rowHeight: React.PropTypes.number,
        headerHeight: React.PropTypes.number,
        headerLabel: React.PropTypes.node,

        //If we should have a checkbox for rows.
        makeRowsSelectable: React.PropTypes.bool,
        //What rows are selected if we have makeRowsSelectable.
        selectedRows: React.PropTypes.array,
        //On a selection if we have makeRowsSelectable.
        onSelection: React.PropTypes.func,

        //Search hint
        searchHint: React.PropTypes.string,
        //If we want or don't want search
        useSearch: React.PropTypes.bool,

        //Trigger functions that haven't already been listed.
        onSearch: React.PropTypes.func,
        onFilter: React.PropTypes.func,
        onSort: React.PropTypes.func,
        onReachedBottom: React.PropTypes.func,
    },
    getDefaultProps() {
        return {
            data: [],
            columns: [],
            columnFilters: {},
            allColumnsThatCouldBeRendered: [],
            makeRowsSelectable: false,

            //Change these to what we'll probably use in prod.
            width: 'auto',
            height: 500,
            rowHeight: 46,
            headerHeight: 50,
            showLoadingComponent: false,
            useSearch: true,
            searchHint: '',
        };
    },
    getInitialState() {
        return {
            showJawbone: false,
        };
    },
    componentDidMount() {
        columnWidthHelper.onChange(() => this.forceUpdate());
        if (this.props.width === 'auto') {
            this._setDynamicWidthOnTable();
            $(window).on('resize', this._setDynamicWidthOnTable);
        } else {
            columnWidthHelper.setTotalWidth(this.props.width);
        }
    },
    _setDynamicWidthOnTable() {
        let width = $(this._holder).width();
        if (this.props.makeRowsSelectable) {
            width -= selectorColumnWidth;
        }
        columnWidthHelper.setTotalWidth(width);
    },
    componentWillUnmount() {
        $(window).off('resize', this._setDynamicWidthOnTable);
        columnWidthHelper.destroyListeners();
    },
    componentWillMount() {
       columnWidthHelper.setIdentifiers(_(this.props.columns).pluck('val'));
    },
    componentWillReceiveProps(nextProps, nextState) {
        if (nextProps.columns.length !== this.props.columns.length) {
            columnWidthHelper.setIdentifiers(_(nextProps.columns).pluck('val'));
        }
    },
    _onColumnResize(newWidth, col) {
        columnWidthHelper.setWidthForIdentifier(col, newWidth);
    },
    _onSearchChange(val) {
        if (typeof this.props.onSearch === 'function') {
            this.props.onSearch(val);
        }
    },
    _onSort(payload) {
        if (typeof this.props.onSort === 'function') {
            this.props.onSort(payload);
        }
    },
    _onColumnChange(newColumns) {
        if (typeof this.props.onColumnChange === 'function') {
            this.props.onColumnChange(newColumns);
        }
    },
    _onScrollEnd(x, y) {
        //onReachedBottom not a function, no need to do anything here then.
        if (typeof this.props.onReachedBottom !== 'function') return;

        const {rowHeight, data, height} = this.props;
        var triggerLimit = rowHeight * 20;
        var totalTableHeight = rowHeight * data.length - height;
        if (y > (totalTableHeight - triggerLimit)) {
            this.props.onReachedBottom();
        }
    },
    _onColumnHover({col}, state) {
        const {columnWidths} = columnWidthHelper.getState();
        const oldWidth = columnWidths[col];
        const newWidth = (state) ? oldWidth + 20 : oldWidth - 20;
        columnWidthHelper.setWidthForIdentifier(col, newWidth);
    },
    _showJawboneFilter() {
        this.setState({ showJawbone: !this.state.showJawbone });
    },
    _onChipRemove(key, val) {
        if (typeof this.props.onFilter === 'function') {
            this.props.onFilter([key, val]);
        }
    },
    render() {
        const data = this.props.data;
        const columnsToRender = this.props.columns;

        const {columnWidths, totalWidth} = columnWidthHelper.getState();
        debug('Column widths are', columnWidths, 'Total width', totalWidth);

        let cols = _(columnsToRender).map((col, index) => {
            const columnWidth = columnWidths[col.val];
            //Last element is not resizable
            const isResizable = (index === columnsToRender.length - 1) ? false : true;
            return (
                <Column
                    columnKey={col.val}
                    key={col.val}
                    {...columnWidth}
                    header={(props) => {
                        const filters = this.props.columnFilters[col.val];
                        const sort = (this.props.sort && this.props.sort.column === col.val)
                                  ? this.props.sort
                                  : null;

                        return <HeaderCell
                            onFilter={this.props.onFilter}
                            sort={sort}
                            onSort={this._onSort}
                            availableFilters={filters}
                            currentFilters={this.props.currentFilters}
                            {...col}
                            {...props} />
                    }}
                    cell={<NormalCell data={data} col={col.val} />}
                    isResizable={isResizable}
                />
            );
        });

        const props = this.props;
        if (props.makeRowsSelectable) {
            const key = 'BP-selector';
            cols.unshift(
                <Column
                    columnKey={key}
                    key={key}
                    isResizable={false}
                    width={selectorColumnWidth}
                    cell={<SelectorCell data={data} onChange={props.onSelection} selections={props.selectedRows} />}
                />
            )
        }

        const tableHeight = props.height;

        const loadingComponent = props.showLoadingComponent
                  ? <LoadingComponent height={tableHeight} numResults={props.data.length}  />
                  : null;

        return (

 this._holder = ref} style={{position: 'relative'}} className='bui-table-holder'>
                <TableHeader
                    onColumnChange={this._onColumnChange}
                    onSearchChange={this._onSearchChange}
                    allColumnsThatCouldBeRendered={props.allColumnsThatCouldBeRendered}
                    currentColumns={columnsToRender}
                    currentFilters={this.props.currentFilters}
                    justifyColumns={columnWidthHelper.justifyColumns.bind(columnWidthHelper)}
                    headerLabel={this.props.headerLabel}
                    showJawboneFilter={this._showJawboneFilter}
                    selections={props.selectedRows}
                    onFilter={this.props.onFilter}
                    searchHint={this.props.searchHint}
                    useSearch={this.props.useSearch}
                />
                <TableJawboneFilter columns={this.props.allColumnsThatCouldBeRendered}
                    onChipRemove={this._onChipRemove}
                    currentFilters={this.props.currentFilters}
                    columnFilters={this.props.columnFilters}

                    visible={this.state.showJawbone} />

                {cols}

                {loadingComponent}

        );
    }
});

const LoadingComponent = React.createClass({
    propTypes: {
        loadingText: React.PropTypes.string,
        height: React.PropTypes.number,
        numResults: React.PropTypes.number,
    },
    getDefaultProps() {
        return {
            loadingText: 'Laddar in fler resultat...',
        };
    },
    render() {
        const {numResults, height} = this.props;

        const hasLoadedResults = numResults > 0;
        const loadingStyle = {
            position: 'absolute',
            bottom: 0,
            width: '100%',

            //50 is headerHeight
            height: (hasLoadedResults) ? 40 : height - 50,
            backgroundColor: (hasLoadedResults) ? 'rgba(255, 255, 255, 0.9)' : 'white',
        };

        const textStyle = {
            paddingLeft: 5,
        };

        const text = (hasLoadedResults) ? '' : this.props.loadingText;

        return (

                <Loader message={text} />

        )
    }
});

export default TableHolderComponent;
<|endoftext|>


<commit_before>import { downloadVideo } from '../downloader/downloader';
import { getDownloads, removeVideoFromDownloads } from '../storage/storage';

const path = require('path');
const fs = require('fs');
const prettyBytes = require('pretty-bytes');
const { shell } = require('electron');

let $datatable;
let $tableParent;

export var init = function () {
  const $table = $('table');
  $tableParent = $table.parent();
  $tableParent.hide();

  $datatable = $('table').DataTable({
    info: false,
    paging: false,
    autoWidth: false,
  });

  const videos = getVideosFromStorage();
  if (videos.length == 0) {
    return;
  }

  $('body').removeClass('center-vertical');

  addStoredVideosToTable(videos);

  $tableParent.show();
};

function getVideosFromStorage() {
  const downloads = getDownloads();
  const videos = [];
  for (const id in downloads) {
    const info = downloads[id];
    try {
      fs.statSync(info.path);
      videos.push(info);
    } catch (error) {
      removeVideoFromDownloads(id);
    }
  }

  return videos;
}

function addStoredVideosToTable(videos) {
  for (const info of videos) {
    const percentage = getVideoDownloadPercentage(info);

    const $tr = $(videoToHTML(info, percentage));
    moveProgressIndicator($tr, percentage);

    $datatable.row.add($tr).draw(false);
  }
}

export var downloadVideoAndUpdateTable = function (link, onError, onSuccess) {
  let $tr;

  downloadVideo(link, onStartDownloading, onProgress, onError, onEnd);

  function onStartDownloading(info) {
    $tr = $(videoToHTML(info));

    $datatable.row.add($tr).draw(false);
    $tableParent.show();

    onVideoAddedToTable();
  }

  function onProgress(percentage) {
    $tr.find('td.status').text(Math.round(percentage) + '%');
    moveProgressIndicator($tr, percentage);
  }

  function onEnd(destinationFilePath) {
    const $button = getShowItemInFolderButton(destinationFilePath);
    $tr.find('td.actions').html($button);
  }
};

function getVideoDownloadPercentage(info) {
  const fileSize = fs.statSync(info.path).size;
  return (fileSize / info.size) * 100.0;
}

function videoToHTML(video, percentage = 0) {
    const trClass = (percentage > 0) ? 'paused' : '';
    let actions = (percentage > 0) ? getResumeButton() : '';
    actions += getCancelAndDeleteButton();

    return '
' +
            '' + video.title + '	' +
            '' + video.uploader + '	' +
            '' + video.duration + '	' +
            '' + prettyBytes(video.size) + '	' +
            '' + Math.round(percentage) + '%	' +
            '' + actions + '	' +
        '
';
}

function getResumeButton() {
    return '<button title="Resume download" class="btn btn-primary btn-sm" disabled>' +
                '' +
            '</button>';
}

function getCancelAndDeleteButton() {
    return '<button title="(Cancel the download and) delete this file" class="btn btn-danger btn-sm" disabled>' +
                '' +
            '</button>';
}

function getShowItemInFolderButton(destinationFilePath) {
    return $('<button title="Open the folder containing this file" class="btn btn-secondary btn-sm">' +
          '' +
      '</button>').on('click', () => shell.showItemInFolder(destinationFilePath))
}

function moveProgressIndicator($tr, percentage) {
  if (percentage === 100) {
    $tr.addClass('done');
  }

  $tr.css('background-size', percentage + '% 1px');
}
<commit_msg>Check if video is not already downloading or has not been entirely downloaded<commit_after>import { downloadVideo } from '../downloader/downloader';
import { getDownloads, getVideoInDownloads, removeVideoFromDownloads } from '../storage/storage';

const path = require('path');
const fs = require('fs');
const prettyBytes = require('pretty-bytes');
const url = require('url');
const { shell } = require('electron');

let $datatable;
let $tableParent;

export var init = function () {
  const $table = $('table');
  $tableParent = $table.parent();
  $tableParent.hide();

  $datatable = $('table').DataTable({
    info: false,
    paging: false,
    autoWidth: false,
  });

  const videos = getVideosFromStorage();
  if (videos.length == 0) {
    return;
  }

  $('body').removeClass('center-vertical');

  addStoredVideosToTable(videos);

  $tableParent.show();
};

function getVideosFromStorage() {
  const downloads = getDownloads();
  const videos = [];
  for (const id in downloads) {
    const info = downloads[id];
    try {
      fs.statSync(info.path);
      videos.push(info);
    } catch (error) {
      removeVideoFromDownloads(id);
    }
  }

  return videos;
}

function addStoredVideosToTable(videos) {
  for (const info of videos) {
    const percentage = getVideoDownloadPercentage(info);

    const $tr = $(videoToHTML(info, percentage));
    moveProgressIndicator($tr, percentage);

    $datatable.row.add($tr).draw(false);
  }
}

export var downloadVideoAndUpdateTable = function (link, onError, onSuccess) {
  let $tr;

  const id = url.parse(link, true).query.v;
  const videoFromStorage = getVideoInDownloads(id);
  if (typeof videoFromStorage !== 'undefined') {
    $tr = $('table').find('tr#' + id);

    if (getVideoDownloadPercentage(videoFromStorage) === 100) {
      $tr.css('background-color', '#00dd00'); // ToDo animate
      onSuccess();
    } else {
      $tr.css('background-color', '#0000dd'); // ToDo animate
      // ToDo resume download
      // downloadVideo(link, onResumeDownloading, onProgress, onError, onEnd, videoFromStorage);
      onSuccess();
    }
  } else {
    downloadVideo(link, onStartDownloading, onProgress, onError, onEnd);
  }

  function onStartDownloading(info) {
    $tr = $(videoToHTML(info));

    $datatable.row.add($tr).draw(false);
    $tableParent.show();

    onSuccess();
  }

  function onProgress(percentage) {
    $tr.find('td.status').text(Math.round(percentage) + '%');
    moveProgressIndicator($tr, percentage);
  }

  function onEnd(destinationFilePath) {
    const $button = getShowItemInFolderButton(destinationFilePath);
    $tr.find('td.actions').html($button);
  }
};

function getVideoDownloadPercentage(info) {
  const fileSize = fs.statSync(info.path).size;
  return (fileSize / info.size) * 100.0;
}

function videoToHTML(video, percentage = 0) {
    const trClass = (percentage > 0) ? 'paused' : '';
    let actions = (percentage > 0) ? getResumeButton() : '';
    actions += getCancelAndDeleteButton();

    return '
' +
            '' + video.title + '	' +
            '' + video.uploader + '	' +
            '' + video.duration + '	' +
            '' + prettyBytes(video.size) + '	' +
            '' + Math.round(percentage) + '%	' +
            '' + actions + '	' +
        '
';
}

function getResumeButton() {
    return '<button title="Resume download" class="btn btn-primary btn-sm" disabled>' +
                '' +
            '</button>';
}

function getCancelAndDeleteButton() {
    return '<button title="(Cancel the download and) delete this file" class="btn btn-danger btn-sm" disabled>' +
                '' +
            '</button>';
}

function getShowItemInFolderButton(destinationFilePath) {
    return $('<button title="Open the folder containing this file" class="btn btn-secondary btn-sm">' +
          '' +
      '</button>').on('click', () => shell.showItemInFolder(destinationFilePath))
}

function moveProgressIndicator($tr, percentage) {
  if (percentage === 100) {
    $tr.addClass('done');
  }

  $tr.css('background-size', percentage + '% 1px');
}
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var partials = require('express-partials');
var methodOverride = require('method-override');
var session = require('express-session');

var routes = require('./routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(partials());

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(favicon(path.join(__dirname, 'public/favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser('!"·$%&/()="'));
app.use(methodOverride('_method'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(session());

// Helpers dinamicos:
app.use(function(req, res, next) {

	// guardar path en session.redir para despues de login
	if (!req.path.match(/\/login/)) {
		req.session.redir = req.path;
	}

	// Hacer visible req.session en las vistas
	res.locals.session = req.session;
	next();
});

app.use('/', routes);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
	var err = new Error('Not Found');
	err.status = 404;
	next(err);
});

// ERROR HANDLERS

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
	app.use(function(err, req, res, next) {
		res.status(err.status || 500);
		res.render('error', {
			message: err.message,
			error: err,
			errors: []
		});
	});
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
	res.status(err.status || 500);
	res.render('error', {
		message: [],
		error: {},
		errors: []
	});
});

module.exports = app;
<commit_msg>Autologout<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var partials = require('express-partials');
var methodOverride = require('method-override');
var session = require('express-session');

var routes = require('./routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(partials());

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(favicon(path.join(__dirname, 'public/favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser('!"·$%&/()="'));
app.use(methodOverride('_method'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(session());

// Helpers dinamicos

app.use(function(req, res, next) {

	// guardar path en session.redir para despues de login
	if (!req.path.match(/\/login/)) {
		req.session.redir = req.path;
	}

	console.log("SESSION");
	console.dir(req.session);
	// autologout
	var now = Date.now();
	var sessionMaxTime = 120000; // 2 min
	if(req.session.lastConn && now - req.session.lastConn > sessionMaxTime){
		delete req.session.user;
	}
	req.session.lastConn = now;
	// ! autologout

	// Hacer visible req.session en las vistas
	res.locals.session = req.session;
	next();
});

app.use('/', routes);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
	var err = new Error('Not Found');
	err.status = 404;
	next(err);
});

// ERROR HANDLERS

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
	app.use(function(err, req, res, next) {
		res.status(err.status || 500);
		res.render('error', {
			message: err.message,
			error: err,
			errors: []
		});
	});
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
	res.status(err.status || 500);
	res.render('error', {
		message: [],
		error: {},
		errors: []
	});
});

module.exports = app;
<|endoftext|>


<commit_before>import './load-polyfill';

import {checkVersion} from './version';
import Tabris from './Tabris';
import Device, {create as createDevice, publishDeviceProperties} from './Device';
import Printer, {create as createPrinter} from './Printer';
import App, {create as createApp} from './App';
import FileSystem, {create as createFileSystem} from './FileSystem';
import {createConsole} from './Console';
import Constraint from './Constraint';
import {addDOMDocument} from './Document';
import Event, {addDOMEventTargetMethods} from './Event';
import {addWindowTimerMethods} from './WindowTimers';
import Storage, {create as createStorage} from './Storage';
import JsxProcessor, {createJsxProcessor} from './JsxProcessor';
import Action from './widgets/Action';
import ActionSheet, {ActionSheetItem} from './ActionSheet';
import ActivityIndicator from './widgets/ActivityIndicator';
import AlertDialog from './AlertDialog';
import Button from './widgets/Button';
import Canvas from './widgets/Canvas';
import CheckBox from './widgets/CheckBox';
import CollectionView from './widgets/CollectionView';
import Color from './Color';
import Console from './Console';
import {format} from './Formatter';
import StackComposite from './widgets/StackComposite';
import StackLayout from './StackLayout';
import Composite from './widgets/Composite';
import ContentView, {create as createContentView} from './widgets/ContentView';
import Crypto from './Crypto';
import Drawer, {create as createDrawer} from './widgets/Drawer';
import DateDialog from './DateDialog';
import EventObject from './EventObject';
import Font from './Font';
import Image from './Image';
import ImageData from './ImageData';
import ImageView from './widgets/ImageView';
import InactivityTimer from './InactivityTimer';
import Layout, {ConstraintLayout} from './Layout';
import LayoutData from './LayoutData';
import Listeners from './Listeners';
import LinearGradient from './LinearGradient';
import Page from './widgets/Page';
import Percent from './Percent';
import Picker from './widgets/Picker';
import Pkcs5 from './Pkcs5';
import ProgressEvent from './ProgressEvent';
import ProgressBar from './widgets/ProgressBar';
import Popover from './Popover';
import NativeObject from './NativeObject';
import NavigationView from './widgets/NavigationView';
import NavigationBar, {create as createNavigationBar} from './widgets/NavigationBar';
import RadioButton from './widgets/RadioButton';
import RefreshComposite from './widgets/RefreshComposite';
import ScrollView from './widgets/ScrollView';
import SearchAction from './widgets/SearchAction';
import Slider from './widgets/Slider';
import StatusBar, {create as createStatusBar} from './widgets/StatusBar';
import Switch from './widgets/Switch';
import Tab from './widgets/Tab';
import TabFolder from './widgets/TabFolder';
import TextInput from './widgets/TextInput';
import TextView from './widgets/TextView';
import TimeDialog from './TimeDialog';
import ToggleButton from './widgets/ToggleButton';
import {patchError} from './util-stacktrace';
import Video from './widgets/Video';
import WebView from './widgets/WebView';
import WebSocket from './WebSocket';
import Widget from './Widget';
import WidgetCollection from './WidgetCollection';
import Worker from './Worker';
import XMLHttpRequest from './XMLHttpRequest';

import {fetch} from './fetch/fetch';
import Headers from './fetch/Headers';
import Request from './fetch/Request';
import Response from './fetch/Response';

if (global.tabris && global.tabris.version) {
  throw new Error('tabris module already loaded. Ensure the module is installed only once.');
}

const tabrisMain = Object.assign(new Tabris(), {
  Action,
  ActionSheet,
  ActionSheetItem,
  ActivityIndicator,
  AlertDialog,
  App,
  Button,
  Canvas,
  CheckBox,
  CollectionView,
  Color,
  ConstraintLayout,
  StackLayout,
  StackComposite,
  Composite,
  Constraint,
  Console,
  ContentView,
  Crypto,
  DateDialog,
  Device,
  Drawer,
  Event,
  EventObject,
  FileSystem,
  Font,
  Image,
  ImageData,
  ImageView,
  InactivityTimer,
  JsxProcessor,
  Layout,
  LayoutData,
  Listeners,
  LinearGradient,
  NativeObject,
  NavigationView,
  NavigationBar,
  Popover,
  Page,
  Percent,
  Picker,
  Printer,
  ProgressBar,
  ProgressEvent,
  RadioButton,
  RefreshComposite,
  ScrollView,
  SearchAction,
  Slider,
  Storage,
  StatusBar,
  Switch,
  Tab,
  TabFolder,
  TextInput,
  TextView,
  TimeDialog,
  ToggleButton,
  Video,
  WebSocket,
  WebView,
  Widget,
  WidgetCollection,
  $: WidgetCollection,
  XMLHttpRequest,
  Worker,
  fetch,
  format,
  Headers,
  Request,
  Response,
});

module.exports = tabrisMain;
global.tabris = tabrisMain;

Object.assign(global, {
  Crypto,
  ImageData,
  ProgressEvent,
  Storage,
  WebSocket,
  XMLHttpRequest,
  fetch,
  Headers,
  Request,
  Response,
  JSX: createJsxProcessor(),
  Worker
});

tabrisMain.on('start', (options) => {
  patchError(Error);
  tabris.app = createApp();
  checkVersion(tabris.version, tabris.app._nativeGet('tabrisJsVersion'));
  if (!options || !options.headless) {
    tabris.contentView = createContentView();
    createLegacyDelegate('contentView');
    tabris.drawer = createDrawer();
    createLegacyDelegate('drawer');
    tabris.navigationBar = createNavigationBar();
    createLegacyDelegate('navigationBar');
    tabris.statusBar = createStatusBar();
    createLegacyDelegate('statusBar');
    tabris.printer = createPrinter();
  }
  tabris.device = createDevice();
  tabris.fs = createFileSystem();
  publishDeviceProperties(tabris.device, global);
  tabris.localStorage = createStorage();
  if (tabris.device.platform === 'iOS') {
    tabris.secureStorage = createStorage(true);
  }
  tabris.crypto = new Crypto();
  if (global.console['print']) {
    global.console = createConsole(global.console);
  }
  tabris.pkcs5 = new Pkcs5();
  global.localStorage = tabrisMain.localStorage;
  global.secureStorage = tabrisMain.secureStorage;
  global.crypto = tabrisMain.crypto;
});
addDOMDocument(global);
addDOMEventTargetMethods(global);
addWindowTimerMethods(global);

function createLegacyDelegate(property) {
  Object.defineProperty(tabrisMain.ui = tabrisMain.ui || {}, property, {
    configurable: true,
    get() {
      console.warn(`ui.${property} is deprecated and will be removed in 3.0.0!`);
      return tabrisMain[property];
    }
  });
}
<commit_msg>Remove legacy delegates for ui object<commit_after>import './load-polyfill';

import {checkVersion} from './version';
import Tabris from './Tabris';
import Device, {create as createDevice, publishDeviceProperties} from './Device';
import Printer, {create as createPrinter} from './Printer';
import App, {create as createApp} from './App';
import FileSystem, {create as createFileSystem} from './FileSystem';
import {createConsole} from './Console';
import Constraint from './Constraint';
import {addDOMDocument} from './Document';
import Event, {addDOMEventTargetMethods} from './Event';
import {addWindowTimerMethods} from './WindowTimers';
import Storage, {create as createStorage} from './Storage';
import JsxProcessor, {createJsxProcessor} from './JsxProcessor';
import Action from './widgets/Action';
import ActionSheet, {ActionSheetItem} from './ActionSheet';
import ActivityIndicator from './widgets/ActivityIndicator';
import AlertDialog from './AlertDialog';
import Button from './widgets/Button';
import Canvas from './widgets/Canvas';
import CheckBox from './widgets/CheckBox';
import CollectionView from './widgets/CollectionView';
import Color from './Color';
import Console from './Console';
import {format} from './Formatter';
import StackComposite from './widgets/StackComposite';
import StackLayout from './StackLayout';
import Composite from './widgets/Composite';
import ContentView, {create as createContentView} from './widgets/ContentView';
import Crypto from './Crypto';
import Drawer, {create as createDrawer} from './widgets/Drawer';
import DateDialog from './DateDialog';
import EventObject from './EventObject';
import Font from './Font';
import Image from './Image';
import ImageData from './ImageData';
import ImageView from './widgets/ImageView';
import InactivityTimer from './InactivityTimer';
import Layout, {ConstraintLayout} from './Layout';
import LayoutData from './LayoutData';
import Listeners from './Listeners';
import LinearGradient from './LinearGradient';
import Page from './widgets/Page';
import Percent from './Percent';
import Picker from './widgets/Picker';
import Pkcs5 from './Pkcs5';
import ProgressEvent from './ProgressEvent';
import ProgressBar from './widgets/ProgressBar';
import Popover from './Popover';
import NativeObject from './NativeObject';
import NavigationView from './widgets/NavigationView';
import NavigationBar, {create as createNavigationBar} from './widgets/NavigationBar';
import RadioButton from './widgets/RadioButton';
import RefreshComposite from './widgets/RefreshComposite';
import ScrollView from './widgets/ScrollView';
import SearchAction from './widgets/SearchAction';
import Slider from './widgets/Slider';
import StatusBar, {create as createStatusBar} from './widgets/StatusBar';
import Switch from './widgets/Switch';
import Tab from './widgets/Tab';
import TabFolder from './widgets/TabFolder';
import TextInput from './widgets/TextInput';
import TextView from './widgets/TextView';
import TimeDialog from './TimeDialog';
import ToggleButton from './widgets/ToggleButton';
import {patchError} from './util-stacktrace';
import Video from './widgets/Video';
import WebView from './widgets/WebView';
import WebSocket from './WebSocket';
import Widget from './Widget';
import WidgetCollection from './WidgetCollection';
import Worker from './Worker';
import XMLHttpRequest from './XMLHttpRequest';

import {fetch} from './fetch/fetch';
import Headers from './fetch/Headers';
import Request from './fetch/Request';
import Response from './fetch/Response';

if (global.tabris && global.tabris.version) {
  throw new Error('tabris module already loaded. Ensure the module is installed only once.');
}

const tabrisMain = Object.assign(new Tabris(), {
  Action,
  ActionSheet,
  ActionSheetItem,
  ActivityIndicator,
  AlertDialog,
  App,
  Button,
  Canvas,
  CheckBox,
  CollectionView,
  Color,
  ConstraintLayout,
  StackLayout,
  StackComposite,
  Composite,
  Constraint,
  Console,
  ContentView,
  Crypto,
  DateDialog,
  Device,
  Drawer,
  Event,
  EventObject,
  FileSystem,
  Font,
  Image,
  ImageData,
  ImageView,
  InactivityTimer,
  JsxProcessor,
  Layout,
  LayoutData,
  Listeners,
  LinearGradient,
  NativeObject,
  NavigationView,
  NavigationBar,
  Popover,
  Page,
  Percent,
  Picker,
  Printer,
  ProgressBar,
  ProgressEvent,
  RadioButton,
  RefreshComposite,
  ScrollView,
  SearchAction,
  Slider,
  Storage,
  StatusBar,
  Switch,
  Tab,
  TabFolder,
  TextInput,
  TextView,
  TimeDialog,
  ToggleButton,
  Video,
  WebSocket,
  WebView,
  Widget,
  WidgetCollection,
  $: WidgetCollection,
  XMLHttpRequest,
  Worker,
  fetch,
  format,
  Headers,
  Request,
  Response,
});

module.exports = tabrisMain;
global.tabris = tabrisMain;

Object.assign(global, {
  Crypto,
  ImageData,
  ProgressEvent,
  Storage,
  WebSocket,
  XMLHttpRequest,
  fetch,
  Headers,
  Request,
  Response,
  JSX: createJsxProcessor(),
  Worker
});

tabrisMain.on('start', (options) => {
  patchError(Error);
  tabris.app = createApp();
  checkVersion(tabris.version, tabris.app._nativeGet('tabrisJsVersion'));
  if (!options || !options.headless) {
    tabris.contentView = createContentView();
    tabris.drawer = createDrawer();
    tabris.navigationBar = createNavigationBar();
    tabris.statusBar = createStatusBar();
    tabris.printer = createPrinter();
  }
  tabris.device = createDevice();
  tabris.fs = createFileSystem();
  publishDeviceProperties(tabris.device, global);
  tabris.localStorage = createStorage();
  if (tabris.device.platform === 'iOS') {
    tabris.secureStorage = createStorage(true);
  }
  tabris.crypto = new Crypto();
  if (global.console['print']) {
    global.console = createConsole(global.console);
  }
  tabris.pkcs5 = new Pkcs5();
  global.localStorage = tabrisMain.localStorage;
  global.secureStorage = tabrisMain.secureStorage;
  global.crypto = tabrisMain.crypto;
});
addDOMDocument(global);
addDOMEventTargetMethods(global);
addWindowTimerMethods(global);
<|endoftext|>