<commit_before>$("#iknow").on("click", function(){
    $("#toHideLocation").toggle();
});

$("#noidea").on("click", function(){
    $("#toHideNoidea").toggle();
});

$('#submitIknow').on('click', function(e){
    var venue = $("#location").val();
    //var venueSearch = 'http://api.artsholland.com/sparql?query=PREFIX+ah%3A+%3Chttp%3A%2F%2Fpurl.org%2Fartsholland%2F1.0%2F%3E%0D%0APREFIX+dc%3A+%3Chttp%3A%2F%2Fpurl.org%2Fdc%2Fterms%2F%3E%0D%0A%0D%0ACONSTRUCT+WHERE+%7B%0D%0A%09%3Fevent+rdf%3Atype+ah%3AEvent+%3B%0D%0A%09%09+++ah%3Avenue+%3Fvenue+%3B%0D%0A%09%09%09ah%3Aproduction+%3Fproduction+.%0D%0A%09%0D%0A%09%3Fproduction+dc%3Atitle+%3Ftitle+.%0D%0A%09%0D%0A%09%3Fvenue+dc%3Atitle+%22'+venue+'%22%40en.%0D%0A%7D%0D%0ALIMIT+10';
    var venueSearch = 'http://api.artsholland.com/sparql?query=PREFIX+geo%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F2003%2F01%2Fgeo%2Fwgs84_pos%23%3E+%0D%0APREFIX+ah%3A+%3Chttp%3A%2F%2Fpurl.org%2Fartsholland%2F1.0%2F%3E%0D%0APREFIX+rdf%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F1999%2F02%2F22-rdf-syntax-ns%23%3E%0D%0APREFIX+dc%3A+%3Chttp%3A%2F%2Fpurl.org%2Fdc%2Fterms%2F%3E%0D%0A%0D%0ACONSTRUCT+WHERE+%7B%0D%0A%09%3Fevent+rdf%3Atype+ah%3AEvent+%3B%0D%0A%09%09+++ah%3Avenue+%3Fvenue+%3B%0D%0A%09%09%09ah%3Aproduction+%3Fproduction+.%0D%0A%09%0D%0A%09%3Fproduction+dc%3Atitle+%3Ftitle+.%0D%0A%09%09%09%09%0D%0A%09%3Fvenue+dc%3Atitle+%22'+venue+'%22%40en+%3B%0D%0A%09%09+++geo%3Along+%3Flong+%3B%0D%0A%09%09+++geo%3Alat+%3Flat+.%0D%0A%09%09+++%09%0D%0A%7D%0D%0ALIMIT+10';
    $.ajax({
         headers: {
             Accept: "text/turtle"
        },
        url: venueSearch,
        type: "GET",
        success: function(response) {
            $.post('/store',data={'data': response}, function(data){
            })
        }
    });

    var query = 'PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#> \n PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n PREFIX ah: <http://purl.org/artsholland/1.0/> \n PREFIX dc: <http://purl.org/dc/terms/> \n SELECT DISTINCT ?title ?long ?lat WHERE { \n    ?event rdf:type ah:Event ; \n          ah:venue ?venue ; \n          ah:production ?production . \n    ?production  dc:title ?title . \n    ?venue dc:title "Melkweg"@en ; \n            geo:long ?long; \n              geo:lat ?lat . \n } LIMIT 10';
    var endpoint = 'http://localhost:8080/openrdf-sesame/repositories/artApp';
    var format = 'JSON';

    $.get('/sparql',data={'endpoint': endpoint, 'query': query, 'format': format}, function(json){
        console.log(JSON.stringify(json.results.bindings[1].title.value));

        try {
            var vars = json.head.vars;

            var ul = $('

');
            ul.addClass('list-group');

            $.each(json.results.bindings, function(index,value){
                var li = $('

');
                li.addClass('list-group-item');

                $.each(vars, function(index, v){
                    var v_type = value[v]['type'];
                    var v_value = value[v]['value'];

                    li.append(''+v+'
');

                    // If the value is a URI, create a hyperlink
                    if (v_type == 'uri') {
                        var a = $('');
                        a.attr('href',v_value);
                        a.text(v_value);
                        li.append(a);
                    // Else we're just showing the value.
                    } else {
                        li.append(v_value);console.log('value '+ value);
                    }
                    li.append('
');

                });
                ul.append(li);

            });
            //$('#toOutputArea').html(ul);
            console.log('Bravo:' + ul);
        } catch(err) {
            //$('#toOutputArea').html('Something went wrong!');
            console.log('Something went wrong');
        }
    });
    /*
    $("#toHideMap").toggle();
        initialize_map();
        //setMarker();*/
});

$('#submitNoidea').on('click', function(e){
        //var venueType = $("#selectGenre option:selected").html();
        var venueType="Muziektheater";
        var lng = "4.890198";
        var lat = "52.37111";
        var locationSearch='http://api.artsholland.com/sparql?query=PREFIX+ah%3A+<http%3A%2F%2Fpurl.org%2Fartsholland%2F1.0%2F>%0D%0APREFIX+geo%3A+<http%3A%2F%2Fwww.w3.org%2F2003%2F01%2Fgeo%2Fwgs84_pos%23>%0D%0APREFIX+rdf%3A+<http%3A%2F%2Fwww.w3.org%2F1999%2F02%2F22-rdf-syntax-ns%23>%0D%0APREFIX+rdfs%3A+<http%3A%2F%2Fwww.w3.org%2F2000%2F01%2Frdf-schema%23>%0D%0A%0D%0ACONSTRUCT+%7B%0D%0A%09%3Fvenue+geo%3Alat+%3Flat.%0D%0A%09%3Fvenue+geo%3Along+%3Flong.%0D%0A%7D%0D%0AWHERE+%7B%0D%0A++%09%3Fevent+rdf%3Atype+ah%3AEvent+%3B%0D%0A%09++++ah%3Avenue+%3Fvenue+%3B%0D%0A%09%09ah%3Aproduction+%3Fproduction.%0D%0A%09%0D%0A%09%3Fproduction+ah%3Agenre+%3Fgenre.%0D%0A%0D%0A%09%3Fgenre+rdfs%3Alabel+%22'+venueType+'%22%5E%5Exsd%3Astring.%0D%0A%09%3Fvenue+geo%3Alat+%3Flat.%0D%0A%09%3Fvenue+geo%3Along+%3Flong.%0D%0A%0D%0AFILTER+%28+%3Flong+%3E+%22'+lng+'%22%5E%5Exsd%3Afloat+-+%220.025%22%5E%5Exsd%3Afloat+%26%26+%3Flong+%3C+%22'+lng+'%22%5E%5Exsd%3Afloat+%2B+%220.025%22%5E%5Exsd%3Afloat+%0D%0A%09%09%26%26+%3Flat+%3E+%22'+lat+'%22%5E%5Exsd%3Afloat+-+%220.015%22%5E%5Exsd%3Afloat+%26%26+%3Flat+%3C+%22'+lat+'%22%5E%5Exsd%3Afloat+%2B+%220.015%22%5E%5Exsd%3Afloat%29%0D%0A%7D%0D%0A%0D%0A+LIMIT+10'

        $.ajax({
            headers: {
                Accept: "text/turtle"
            },
        url: locationSearch,
        type: "GET",
        success: function(response) {
            $.post('/store',data={'data': response}, function(response){
            })
        }
    });
});

function initialize_map(){
    var latlng = new google.maps.LatLng(0, 0);
    var mapOptions = {
            zoom : 2,
            mapTypeId : google.maps.MapTypeId.ROADMAP,
            center :  latlng
        };

        map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
<commit_msg>added map stuff and hopefully nice event output<commit_after>var map;
$("#iknow").on("click", function(){
    $("#toHideLocation").toggle();
});

$("#noidea").on("click", function(){
    $("#toHideNoidea").toggle();
});

$('#submitIknow').on('click', function(e){
    var venue = $("#location").val();
    //var venueSearch = 'http://api.artsholland.com/sparql?query=PREFIX+ah%3A+%3Chttp%3A%2F%2Fpurl.org%2Fartsholland%2F1.0%2F%3E%0D%0APREFIX+dc%3A+%3Chttp%3A%2F%2Fpurl.org%2Fdc%2Fterms%2F%3E%0D%0A%0D%0ACONSTRUCT+WHERE+%7B%0D%0A%09%3Fevent+rdf%3Atype+ah%3AEvent+%3B%0D%0A%09%09+++ah%3Avenue+%3Fvenue+%3B%0D%0A%09%09%09ah%3Aproduction+%3Fproduction+.%0D%0A%09%0D%0A%09%3Fproduction+dc%3Atitle+%3Ftitle+.%0D%0A%09%0D%0A%09%3Fvenue+dc%3Atitle+%22'+venue+'%22%40en.%0D%0A%7D%0D%0ALIMIT+10';
    var venueSearch = 'http://api.artsholland.com/sparql?query=PREFIX+geo%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F2003%2F01%2Fgeo%2Fwgs84_pos%23%3E+%0D%0APREFIX+ah%3A+%3Chttp%3A%2F%2Fpurl.org%2Fartsholland%2F1.0%2F%3E%0D%0APREFIX+rdf%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F1999%2F02%2F22-rdf-syntax-ns%23%3E%0D%0APREFIX+dc%3A+%3Chttp%3A%2F%2Fpurl.org%2Fdc%2Fterms%2F%3E%0D%0A%0D%0ACONSTRUCT+WHERE+%7B%0D%0A%09%3Fevent+rdf%3Atype+ah%3AEvent+%3B%0D%0A%09%09+++ah%3Avenue+%3Fvenue+%3B%0D%0A%09%09%09ah%3Aproduction+%3Fproduction+.%0D%0A%09%0D%0A%09%3Fproduction+dc%3Atitle+%3Ftitle+.%0D%0A%09%09%09%09%0D%0A%09%3Fvenue+dc%3Atitle+%22'+venue+'%22%40en+%3B%0D%0A%09%09+++geo%3Along+%3Flong+%3B%0D%0A%09%09+++geo%3Alat+%3Flat+.%0D%0A%09%09+++%09%0D%0A%7D%0D%0ALIMIT+10';
    $.ajax({
         headers: {
             Accept: "text/turtle"
        },
        url: venueSearch,
        type: "GET",
        success: function(response) {
            $.post('/store',data={'data': response}, function(data){
            })
        }
    });

    var query = 'PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#> \n PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n PREFIX ah: <http://purl.org/artsholland/1.0/> \n PREFIX dc: <http://purl.org/dc/terms/> \n SELECT DISTINCT ?title ?long ?lat WHERE { \n    ?event rdf:type ah:Event ; \n          ah:venue ?venue ; \n          ah:production ?production . \n    ?production  dc:title ?title . \n    ?venue dc:title "Melkweg"@en ; \n            geo:long ?long; \n              geo:lat ?lat . \n } LIMIT 10';
    var endpoint = 'http://localhost:8080/openrdf-sesame/repositories/artApp';
    var format = 'JSON';

    $.get('/sparql',data={'endpoint': endpoint, 'query': query, 'format': format}, function(json){

    var lat = json.results.bindings[0].lat.value;
    var lng = json.results.bindings[0].long.value;

          //$("#toHideMap").toggle();
        initialize_map();
        setMarker(lat, lng, venue);
        try {

            var vars = json.head.vars;

            var ul = $('

');
            ul.addClass('list-group');
            var pre = $('

');

            $.each(json.results.bindings, function(index,value){
                var li = $('

');
                li.addClass('list-group-item');

                $.each(vars, function(index, v){

                    if (index == 0) {
                        console.log(value.title.value);
                        pre.text(value.title.value);

                        li.append(''+value+'
');
                        li.append(value.title.value);
                        li.append('
');
                    }
                });
                ul.append(li);

            });
            $('#tlinkOutput').html(ul);
            console.log('Bravo:' + ul);
        } catch(err) {
            $('#linkOutput').html('Something went wrong!');
            console.log('Something went wrong');
        }
    });
    /*
    $("#toHideMap").toggle();
        initialize_map();
        //setMarker();*/
});

$('#submitNoidea').on('click', function(e){
    //var venueType = $("#selectGenre option:selected").html();
    var venueType="Muziektheater";
    var lng = "4.890198";
    var lat = "52.37111";
    var locationSearch='http://api.artsholland.com/sparql?query=PREFIX+ah%3A+<http%3A%2F%2Fpurl.org%2Fartsholland%2F1.0%2F>%0D%0APREFIX+geo%3A+<http%3A%2F%2Fwww.w3.org%2F2003%2F01%2Fgeo%2Fwgs84_pos%23>%0D%0APREFIX+rdf%3A+<http%3A%2F%2Fwww.w3.org%2F1999%2F02%2F22-rdf-syntax-ns%23>%0D%0APREFIX+rdfs%3A+<http%3A%2F%2Fwww.w3.org%2F2000%2F01%2Frdf-schema%23>%0D%0A%0D%0ACONSTRUCT+%7B%0D%0A%09%3Fvenue+geo%3Alat+%3Flat.%0D%0A%09%3Fvenue+geo%3Along+%3Flong.%0D%0A%7D%0D%0AWHERE+%7B%0D%0A++%09%3Fevent+rdf%3Atype+ah%3AEvent+%3B%0D%0A%09++++ah%3Avenue+%3Fvenue+%3B%0D%0A%09%09ah%3Aproduction+%3Fproduction.%0D%0A%09%0D%0A%09%3Fproduction+ah%3Agenre+%3Fgenre.%0D%0A%0D%0A%09%3Fgenre+rdfs%3Alabel+%22'+venueType+'%22%5E%5Exsd%3Astring.%0D%0A%09%3Fvenue+geo%3Alat+%3Flat.%0D%0A%09%3Fvenue+geo%3Along+%3Flong.%0D%0A%0D%0AFILTER+%28+%3Flong+%3E+%22'+lng+'%22%5E%5Exsd%3Afloat+-+%220.025%22%5E%5Exsd%3Afloat+%26%26+%3Flong+%3C+%22'+lng+'%22%5E%5Exsd%3Afloat+%2B+%220.025%22%5E%5Exsd%3Afloat+%0D%0A%09%09%26%26+%3Flat+%3E+%22'+lat+'%22%5E%5Exsd%3Afloat+-+%220.015%22%5E%5Exsd%3Afloat+%26%26+%3Flat+%3C+%22'+lat+'%22%5E%5Exsd%3Afloat+%2B+%220.015%22%5E%5Exsd%3Afloat%29%0D%0A%7D%0D%0A%0D%0A+LIMIT+10'

    $.ajax({
        headers: {
            Accept: "text/turtle"
        },
        url: locationSearch,
        type: "GET",
        success: function(response) {
            $.post('/store',data={'data': response}, function(response){
            })
        }
    });
});

function initialize_map(){
    var myLatlng = new google.maps.LatLng(0,0);

    var mapOptions = {
        zoom: 2,
        center: myLatlng
    }

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

function setMarker(lat, lng, venue){
    var myLatlng = new google.maps.LatLng(lat,lng);
    map.setCenter(myLatlng);
    map.setZoom(12);
    var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: venue
    });
}
<|endoftext|>


<commit_before>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var net = require('net');
var debug = require('debug')('mintpeaks:server');

// Tessel TCP server settings.
var TESSEL_SERVER_HOST = '0.0.0.0';
var TESSEL_SERVER_PORT = 10231;

// HTTP server settings.
var HTTP_SERVER_PORT = 3000;

// Socket.io connection logging.
io.on('connection', function(sckt) {
  debug('Browser connected');

   sckt.on('disconnect', function() {
    debug('Browser disconnected');
  });
});

// Start up HTTP server.
http.listen(HTTP_SERVER_PORT, function() {
  debug('HTTP server listening on *:' + HTTP_SERVER_PORT);
});

// Callback runs for each created connection.
net.createServer(function(sckt) {
  // A connection was initiated.
  debug('Tessel connected', sckt.remoteAddress, sckt.remotePort);

  sckt.on('data', function(data) {
    data = data.toString('utf8');

    try {
      var parsed_data = JSON.parse(data);
      debug('Received data from Tessel', parsed_data);

      // Emit received data through Socket.io.
      io.emit('received_data', parsed_data);
    } catch (e) {
      debug('ERROR: Received non JSON data from Tessel', data);
    }
  });

  // Connection closed handler.
  sckt.on('close', function() {
    debug('Tessel disconnected');
  });
}).listen(TESSEL_SERVER_PORT, TESSEL_SERVER_HOST);

debug('Tessel server listening on ' + TESSEL_SERVER_HOST + ':' + TESSEL_SERVER_PORT);
<commit_msg>Heartbeat functionality tells the browser whether the Tessel is connected.<commit_after>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var net = require('net');
var debug = require('debug')('mintpeaks:server');

// Tessel TCP server settings.
var TESSEL_SERVER_HOST = '0.0.0.0';
var TESSEL_SERVER_PORT = 10231;
var TESSEL_CONNECTED = false;
var TESSEL_HEARTBEAT = null;

// HTTP server settings.
var HTTP_SERVER_PORT = 3000;

// Socket.io connection logging.
io.on('connection', function(sckt) {
  debug('Browser connected');

   sckt.on('disconnect', function() {
    debug('Browser disconnected');
  });
});

// Start up HTTP server.
http.listen(HTTP_SERVER_PORT, function() {
  debug('HTTP server listening on *:' + HTTP_SERVER_PORT);
});

// Callback runs for each created connection.
net.createServer(function(sckt) {
  // A connection was initiated.
  debug('Tessel connected', sckt.remoteAddress, sckt.remotePort);
  TESSEL_CONNECTED = true;

  sckt.on('data', function(data) {
    data = data.toString('utf8');

    try {
      var parsed_data = JSON.parse(data);
      debug('Received data from Tessel', parsed_data);

      // Emit received data through Socket.io.
      io.emit('received_data', parsed_data);

      // Reset the Tessel heartbeat timer.
      clearTimeout(TESSEL_HEARTBEAT);
      TESSEL_HEARTBEAT = setTimeout(function() { TESSEL_CONNECTED = false; }, 10000);
    } catch (e) {
      debug('ERROR: Received non JSON data from Tessel', data);
    }
  });

  // Connection closed handler.
  sckt.on('close', function() {
    debug('Tessel disconnected');
    TESSEL_CONNECTED = false;
  });
}).listen(TESSEL_SERVER_PORT, TESSEL_SERVER_HOST);

debug('Tessel server listening on ' + TESSEL_SERVER_HOST + ':' + TESSEL_SERVER_PORT);

// Send over heartbeat.
setInterval(function() {
  io.emit('hearbeat', { mintpeaks: true, tessel: TESSEL_CONNECTED });
}, 2500);
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import styled from 'react-emotion';

import ReactModal from 'react-modal';
import FuzzySearch from 'react-fuzzy';
import { baseFonts } from '@storybook/components';

const modalStyle = {
  content: {
    top: '100px',
    right: 'auto',
    bottom: 'auto',
    left: '50%',
    marginLeft: '-215px',
    border: 'none',
    padding: 0,
    overflow: 'visible',
    ...baseFonts,
  },
  overlay: {
    background: 'transparent',
    zIndex: '1',
  },
};

const formatStories = stories => {
  const formattedStories = [];
  let i = 0;
  stories.forEach(val => {
    i += 1;
    formattedStories.push({
      type: 'kind',
      value: val.kind,
      id: i,
    });

    val.stories.forEach(story => {
      i += 1;
      formattedStories.push({
        type: 'story',
        value: story,
        id: i,
        kind: val.kind,
      });
    });
  });

  return formattedStories;
};

const SuggestionWrapper = styled('div')(
  ({ selected, selectedResultStyle, resultsStyle }) =>
    selected ? selectedResultStyle : resultsStyle,
  { display: 'flex', justifyContent: 'space-between' }
);
const SuggestionValue = styled('p')({ margin: 0 });
const SuggestionKind = styled('p')({
  opacity: 0.5,
  margin: 0,
  paddingLeft: 10,
  textAlign: 'right',
});

const suggestionTemplate = (props, state, styles, clickHandler) =>
  state.results.map((val, i) => (
    <SuggestionWrapper
      selected={state.selectedIndex === i}
      {...styles}
      tabIndex={0}
      role="option"
      aria-selected={state.selectedIndex === i}
      key={`${val.value}_${val.id}`}
      onClick={() => clickHandler(i)}
    >
      <SuggestionValue>{val.value}</SuggestionValue>
      <SuggestionKind>{val.type === 'story' ? `in ${val.kind}` : 'Kind'}</SuggestionKind>
    </SuggestionWrapper>
  ));

export default class SearchBox extends React.Component {
  constructor(props) {
    super(props);

    this.onSelect = this.onSelect.bind(this);
    this.fireOnStory = this.fireOnStory.bind(this);
    this.fireOnKind = this.fireOnKind.bind(this);
    this.inputRef = this.inputRef.bind(this);
    this.onModalOpen = this.onModalOpen.bind(this);
  }

  onSelect(selected) {
    const { onClose } = this.props;
    if (selected.type === 'story') {
      this.fireOnStory(selected.value, selected.kind);
    } else {
      this.fireOnKind(selected.value);
    }
    onClose();
  }

  onModalOpen() {
    if (this.input != null) {
      this.input.focus();
    }
  }

  fireOnKind(kind) {
    const { onSelectStory } = this.props;
    if (onSelectStory) {
      onSelectStory(kind, null);
    }
  }

  fireOnStory(story, kind) {
    const { onSelectStory } = this.props;
    if (onSelectStory) {
      onSelectStory(kind, story);
    }
  }

  inputRef(fuzzy) {
    if (fuzzy != null) {
      this.input = fuzzy.refs.searchBox;
    }
  }

  render() {
    return (
      <ReactModal
        isOpen={this.props.showSearchBox}
        onAfterOpen={this.onModalOpen}
        onRequestClose={this.props.onClose}
        style={modalStyle}
        contentLabel="Search"
        shouldReturnFocusAfterClose={false}
      >
        <FuzzySearch
          list={formatStories(this.props.stories)}
          onSelect={this.onSelect}
          keys={['value', 'type']}
          resultsTemplate={suggestionTemplate}
          innerRef={inputRef => {
            this.inputRef = inputRef;
          }}
        />
      </ReactModal>
    );
  }
}

SearchBox.defaultProps = { stories: [] };

SearchBox.propTypes = {
  showSearchBox: PropTypes.bool.isRequired,
  stories: PropTypes.arrayOf(PropTypes.object),
  onSelectStory: PropTypes.func.isRequired,
  onClose: PropTypes.func.isRequired,
};
<commit_msg>REMOVE basefonts from searchbox<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import styled from 'react-emotion';

import ReactModal from 'react-modal';
import FuzzySearch from 'react-fuzzy';

const modalStyle = {
  content: {
    top: '100px',
    right: 'auto',
    bottom: 'auto',
    left: '50%',
    marginLeft: '-215px',
    border: 'none',
    padding: 0,
    overflow: 'visible',
  },
  overlay: {
    background: 'transparent',
    zIndex: '1',
  },
};

const formatStories = stories => {
  const formattedStories = [];
  let i = 0;
  stories.forEach(val => {
    i += 1;
    formattedStories.push({
      type: 'kind',
      value: val.kind,
      id: i,
    });

    val.stories.forEach(story => {
      i += 1;
      formattedStories.push({
        type: 'story',
        value: story,
        id: i,
        kind: val.kind,
      });
    });
  });

  return formattedStories;
};

const SuggestionWrapper = styled('div')(
  ({ selected, selectedResultStyle, resultsStyle }) =>
    selected ? selectedResultStyle : resultsStyle,
  { display: 'flex', justifyContent: 'space-between' }
);
const SuggestionValue = styled('p')({ margin: 0 });
const SuggestionKind = styled('p')({
  opacity: 0.5,
  margin: 0,
  paddingLeft: 10,
  textAlign: 'right',
});

const suggestionTemplate = (props, state, styles, clickHandler) =>
  state.results.map((val, i) => (
    <SuggestionWrapper
      selected={state.selectedIndex === i}
      {...styles}
      tabIndex={0}
      role="option"
      aria-selected={state.selectedIndex === i}
      key={`${val.value}_${val.id}`}
      onClick={() => clickHandler(i)}
    >
      <SuggestionValue>{val.value}</SuggestionValue>
      <SuggestionKind>{val.type === 'story' ? `in ${val.kind}` : 'Kind'}</SuggestionKind>
    </SuggestionWrapper>
  ));

export default class SearchBox extends React.Component {
  constructor(props) {
    super(props);

    this.onSelect = this.onSelect.bind(this);
    this.fireOnStory = this.fireOnStory.bind(this);
    this.fireOnKind = this.fireOnKind.bind(this);
    this.inputRef = this.inputRef.bind(this);
    this.onModalOpen = this.onModalOpen.bind(this);
  }

  onSelect(selected) {
    const { onClose } = this.props;
    if (selected.type === 'story') {
      this.fireOnStory(selected.value, selected.kind);
    } else {
      this.fireOnKind(selected.value);
    }
    onClose();
  }

  onModalOpen() {
    if (this.input != null) {
      this.input.focus();
    }
  }

  fireOnKind(kind) {
    const { onSelectStory } = this.props;
    if (onSelectStory) {
      onSelectStory(kind, null);
    }
  }

  fireOnStory(story, kind) {
    const { onSelectStory } = this.props;
    if (onSelectStory) {
      onSelectStory(kind, story);
    }
  }

  inputRef(fuzzy) {
    if (fuzzy != null) {
      this.input = fuzzy.refs.searchBox;
    }
  }

  render() {
    return (
      <ReactModal
        isOpen={this.props.showSearchBox}
        onAfterOpen={this.onModalOpen}
        onRequestClose={this.props.onClose}
        style={modalStyle}
        contentLabel="Search"
        shouldReturnFocusAfterClose={false}
      >
        <FuzzySearch
          list={formatStories(this.props.stories)}
          onSelect={this.onSelect}
          keys={['value', 'type']}
          resultsTemplate={suggestionTemplate}
          innerRef={inputRef => {
            this.inputRef = inputRef;
          }}
        />
      </ReactModal>
    );
  }
}

SearchBox.defaultProps = { stories: [] };

SearchBox.propTypes = {
  showSearchBox: PropTypes.bool.isRequired,
  stories: PropTypes.arrayOf(PropTypes.object),
  onSelectStory: PropTypes.func.isRequired,
  onClose: PropTypes.func.isRequired,
};
<|endoftext|>


<commit_before>'use strict'

module.exports = (function(){
    const footballDb = require('./../db/footballDb')
    const express = require('express')
    const router = express.Router()

    router.get('/leagueTable/:id', (req, res, next) => {
        const id = req.params.id
        footballDb
            .leagueTable(id)
            .then(league => {
                league.title = 'League Table'
                res.render('football/leagueTable', league)
            })
    })

    router.get('/leagues', (req, res, next) => {
        footballDb
            .leagues()
            .then(leagues => {
                leagues = leaguesWithLinks(leagues)
                res.render('football/leagues', {
                    'title':'Leagues',
                    'leagues': leagues
                })
            })
    })
    return router

    /**
     * Utility auxiliary function
     */
    function leaguesWithLinks(leagues) {
        return leagues.map(item => {
            item.leagueHref = "/leagueTable/" + item.id
            return item
        })
    }
})()<commit_msg>Missing catch error<commit_after>'use strict'

module.exports = (function(){
    const footballDb = require('./../db/footballDb')
    const express = require('express')
    const router = express.Router()

    router.get('/leagueTable/:id', (req, res, next) => {
        const id = req.params.id
        footballDb
            .leagueTable(id)
            .then(league => {
                league.title = 'League Table'
                res.render('football/leagueTable', league)
            })
            .catch(err => next(err))
    })

    router.get('/leagues', (req, res, next) => {
        footballDb
            .leagues()
            .then(leagues => {
                leagues = leaguesWithLinks(leagues)
                res.render('football/leagues', {
                    'title':'Leagues',
                    'leagues': leagues
                })
            })
            .catch(err => next(err))
    })
    return router

    /**
     * Utility auxiliary function
     */
    function leaguesWithLinks(leagues) {
        return leagues.map(item => {
            item.leagueHref = "/leagueTable/" + item.id
            return item
        })
    }
})()<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var debug = require('debug')('app:middleware');

module.exports = function(anden){
	debug('MIDDLEWARE APP %s running', __filename);

	var staticPath = path.resolve('public');
	debug('[%s] use express static %s %s', anden.name, staticPath);
    anden.app.use(anden.app.express.static(staticPath));
};<commit_msg>EXAMPLE: wip app middleware<commit_after>'use strict';
var path = require('path');
var debug = require('debug')('app:middleware');

module.exports = function(anden){
	debug('MIDDLEWARE APP %s running', __filename);

	return;

	var staticPath = path.resolve('public');
	debug('[%s] use express static %s %s', anden.name, staticPath);
    anden.app.use(anden.app.express.static(staticPath));
};<|endoftext|>


<commit_before>$.fn.tabs = function () {
    $(this).delegate("a:not(.youarehere)", "click", function () {
        if (this.id == "graphTabButton") {
            $("#gridStats").hide();
        } else {
            $("#gridStats").show();
        }
        $(this.hash).show();
        $(this).addClass("youarehere")
               .siblings(".youarehere")
               .removeClass("youarehere").each(function () {
                   $(this.hash).hide();
               });
    }).delegate("a", "click", function () {
        return false;
    });
};

var showingGraph = false;

function encodeColumn(s) {
    if (s != null && s.replace != null) {
        s = s.replace(/[\n\r]/g, " ")
              .replace(/&(?!\w+([;\s]|$))/g, "&")
              .replace(/</g, "<")
              .replace(/>/g, ">")
              .substring(0, 400);
        return s;
    } else {
        return s;
    }
}

function splitTags(s) {
    if (s == null) return [];
    var tmp = s.split("<");
    var rval = [];
    for (var i = 0; i < tmp.length; i++) {
        if (tmp[i] != "") {
            rval.push(tmp[i].replace(">", ""));
        }
    }

    return rval;
}

var current_results;

function scrollToResults() {
    var target_offset = $("#toolbar").offset();
    var target_top = target_offset.top - 10;
    $('html, body').animate({ scrollTop: target_top }, 500);
}

// this is from SO 901115
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

function populateParamsFromUrl() {
    $('#queryParams').find("p input").each(function () {
        var val = getParameterByName(this.name);
        if (val != null && val.length > 0) {
            $(this).val(getParameterByName(this.name));
        }
    });
}

function displayCaptcha() {
    $('form input[type=submit]').hide();
    $('#captcha').show();

    $("#recaptcha_response_field").keydown(function (key) {
        if (key.keyCode == 13) {
            $("#btn-captcha").click();
            return false;
        }
        return true;
    }).focus();

    var captcha = function () {
        $(this).unbind("click");
        $.ajax({
            url: '/captcha',
            data: $('#captcha').closest('form').serialize(),
            type: 'POST',
            success: function (data) {
                if (data.success) {
                    $('form input[type=submit]').show();
                    $('#captcha').hide();
                    $('#captcha').closest('form').submit();
                } else {
                    $("#captcha-error").fadeIn();
                    $("#btn-captcha").click(captcha);
                    var text = $("#recaptcha_response_field");
                    var once = function () { $("#captcha-error").fadeOut(); text.unbind("keydown", once) };
                    text.keydown(once);
                }
            },
            dataType: "json"
        });

    };

    $("#btn-captcha").click(captcha);
}

function isGraph(resultSet) {
    return resultSet.columns.length == 2 &&
        (resultSet.columns[0]["type"] == 'Date' || resultSet.columns[0]["type"] == 'Number') &&
        resultSet.columns[1]["type"] == 'Number'
}

function showTooltip(x, y, contents) {
    $('
' + contents + '<\/div>').css({
        position: 'absolute',
        display: 'none',
        top: y + 5,
        left: x + 5,
        border: '1px solid #fdd',
        padding: '2px',
        'background-color': '#fee',
        opacity: 0.80
    }).appendTo("body").fadeIn(200);
}

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function bindToolTip(graph, suffix) {
    var previousPoint = null;
    var lastCall = 0;
    graph.bind("plothover", function (event, pos, item) {

        var toolTip;

        if (item) {

            if (previousPoint == null || previousPoint[0] != item.datapoint[0] || previousPoint[1] != item.datapoint[1]) {
                previousPoint = item.datapoint;

                $("#tooltip").remove();
                var x = item.datapoint[0].toFixed(2),
                    y = item.datapoint[1].toFixed(2);

                showTooltip(item.pageX - 10, item.pageY - 40, addCommas(parseInt(y)) + suffix);
            }
        }
        else {
            if (previousPoint != null) {
                $("#tooltip").remove();
            }
            previousPoint = null;
        }

    });
}

function renderGraph(resultSet) {

    var options = {
        legend: { position: "nw" },
        grid: { hoverable: true },
        selection: { mode: "x" },
        series: { lines: { show: true }, points: { show: true} }
    };
    if (resultSet.columns[0]["type"] == 'Date') {
        options.xaxis = { mode: "time" };
    }
    var graph = $("#graph");
    $.plot(graph, [resultSet.rows], options);
    bindToolTip(graph, "");
}

function gotResults(results) {

    $(".loading").hide();
    $('form input[type=submit]').attr('disabled', null);

    if (results && results.captcha) {
        displayCaptcha();
        return;
    }

    current_results = results;

    if (results.resultSets && isGraph(results.resultSets[0])) {
        $('#graphTabButton').show();
        var width = document.documentElement.clientWidth;
        if (width < 950) { width = 950; }
        $("#graph").width(width - 90);
        $("#queryResults").width(width - 70);
        $("#gridStats").width(width - 80);
        showingGraph = true;
        renderGraph(results.resultSets[0]);
    }
    else {
        showingGraph = false;
        $('#graphTabButton').hide();
    }

    if (results.error != null) {
        $("#queryErrorBox").show();
        $("#queryError").html(results.error);
        return;
    }

    if (results.truncated == true) {
        $("#queryErrorBox").show();
        $("#queryError").html("Your query was truncated, only " + results.maxResults + " results are allowed");
    }

    $("#messages pre code").text(results.messages);

    var currentParams = "?";
    currentParams += $('#queryParams').find("p input").serialize();

    if (currentParams == "?") {
        currentParams = "";
    }

    $("#permalinks").show();
    var currentLink = $("#permalink")[0];

    var linkId = results.queryId;
    var slug = results.slug == null ? "/" : "/" + results.slug;
    var linkPath = results.textOnly ? "qt" : "q";
    if (window.queryId !== undefined) {
        linkId = queryId;
        slug = "/" + querySlug;
        linkPath = results.textOnly ? "st" : "s";
    }

    currentLink.href = "/" + results.siteName + "/"+ linkPath + "/" + linkId + slug + currentParams;

    $("#downloadCsv")[0].href = "/" + results.siteName + "/" + (results.excludeMetas ? "n" : "") + (results.multiSite ? "m" : "") + "csv/" + results.queryId + currentParams;

    $(".otherPermalink").each(function () {
        // slug
        this.href = this.href.substring(0, this.href.lastIndexOf("/"));
        // query id
        this.href = this.href.substring(0, this.href.lastIndexOf("/"));
        // type
        this.href = this.href.substring(0, this.href.lastIndexOf("/") + 1) + linkPath + "/" + linkId + slug;
    });

    $("#gridStats .duration").text("Duration: " + results.executionTime + "ms");

    if (results.executionPlan && results.executionPlan.length > 0) {
        $("#planTabButton").show();

        $("#executionPlan").html(results.executionPlan);
        QP.drawLines();

        $("#downloadPlan")[0].href = "/" + results.siteName + "/" + (results.excludeMetas ? "n" : "") + (results.multiSite ? "m" : "") + "plan/" + results.queryId + currentParams;
        $("#downloadPlan").show();
    }
    else {
        $("#planTabButton").hide();
        $("#downloadPlan").hide();
    }

    if (results.textOnly || results.resultSets.length == 0) {
        $("#messagesTabButton").click();
        $("#resultsTabButton").hide();

        $("#queryResults").show();
        return;
    }

    $("#resultsTabButton").show();
    $("#resultsTabButton").click();
    $("#grid").show();
    $("#messages").hide();

    var model = [];
    var maxWidths = [];

    for (var c = 0; c < results.resultSets[0].columns.length; c++) {
        model.push({
            width: 60,
            cssClass: (results.resultSets[0].columns[c].type == "Number" ? "number" : "text"),
            id: results.resultSets[0].columns[c].name,
            name: results.resultSets[0].columns[c].name,
            field: c
        });
        maxWidths.push(results.resultSets[0].columns[c].name.length);
    }

    var rows = [];
    var hasTags = false;

    for (var i = 0; i < results.resultSets[0].rows.length; i++) {
        var row = {};

        for (var c = 0; c < results.resultSets[0].columns.length; c++) {
            var data = null;
            var col = results.resultSets[0].rows[i][c];
            if (col != null && col.title != null && col.id != null) {
                var specialType = results.resultSets[0].columns[c].type;
                var baseUrl;
                switch (specialType) {
                    case "User":
                        baseUrl = "/users/";
                        break;
                    case "Post":
                        baseUrl = "/questions/"
                        break;
                    case "SuggestedEdit":
                        baseUrl = "/suggested-edits/"
                        break;
                    default:
                        baseUrl = "invalid";
                }

                data = ("" + encodeColumn(col.title) + "");
                if (col.title.length > maxWidths[c]) maxWidths[c] = col.title.length;
            } else if (model[c].field == "Tags" || model[c].field == "TagName") {
                // smart rendering of tags
                var tags = splitTags(col);
                var tmpLength = tags.join(" ").length;
                if (col != null && tmpLength > maxWidths[c]) maxWidths[c] = tmpLength;
                for (var tagIndex = 0; tagIndex < tags.length; tagIndex++) {
                    tags[tagIndex] = "" + tags[tagIndex] + "";
                };
                data = tags.join(" ");
                hasTags = true;
            } else {
                if (results.resultSets[0].columns[c]["type"] == "Date") {
                    data = (new Date(col)).toString("yyyy-MM-dd HH:mm:ss");
                } else {
                    data = (encodeColumn(col));
                }
                if (data != null && data.toString().length > maxWidths[c]) maxWidths[c] = data.toString().length;
            }
            row[c] = data;
        }
        rows.push(row);
    }

    for (var i = 0; i < model.length; i++) {
        model[i].width = maxWidths[i] * 12 > 250 ? 300 : 8 + maxWidths[i] * 12;
    }

    $("#queryResults").show();
    $("#gridStats .rows").text("" + rows.length + " row" + (rows.length == 1 ? "" : "s"));

    var options = {
        enableCellNavigation: false,
        enableColumnReorder: false,
        rowHeight: hasTags ? 35 : 25
    };

    var grid = new Slick.Grid($("#grid"), rows, model, options);
    grid.onColumnsResized = function () { $("#grid").resize() };

    scrollToResults();

    $("#queryResults").insertAfter('.page:first').css({ 'padding': '0 30px', 'margin': '0 auto' });
    $("#grid").resize();
}

function executeQuery(sql) {
    $("#permalinks, #queryResults, #queryErrorBox").hide();

    if (!ensureAllParamsEntered(sql)) {
        return false;
    }

    $(".loading").show();
    $('#runQueryForm input[type=submit]', this).attr('disabled', 'disabled');

    $.ajax({
      cache: false,
      url: $('#runQueryForm')[0].action,
      type: "POST",
      data: $("#runQueryForm").serialize(),
      error: function () {
        alert("Something is wrong with the server!");
      },
      success: gotResults
    });

    return false;
}

function ensureAllParamsEntered(query) {
    var pattern = /##([a-zA-Z0-9]+):?([a-zA-Z]+)?##/g;
    var params = query.match(pattern);
    if (params == null) params = [];

    var div = $('#queryParams');

    var allParamsHaveValues = true;

    for (var i = 0; i < params.length; i++) {
        params[i] = params[i].substring(2, params[i].length - 2);
        var colonPos = params[i].indexOf(":");
        if (colonPos > 0) {
            params[i] = params[i].substring(0, colonPos);
        }

        var currentParam = div.find("input[name=" + params[i] + "]");
        if (currentParam.length == 0) {
            div.append("
" + params[i] + "\n" +
            "<input type=\"text\" name=\"" + params[i] + "\" value=\"\" />

");
            allParamsHaveValues = false;
        } else {
            if (currentParam.val().length == 0) {
                allParamsHaveValues = false;
            }
        }
    }

    // remove extra params
    div.children("p").each(function () {
        var name = $(this).find('input').attr('name');
        var found = false;
        for (var i = 0; i < params.length; i++) {
            found = params[i] == name;
            if (found) break;
        }
        if (!found) {
            $(this).remove();
        } else {
            // auto param
            if ($(this).find('input').val().length == 0 && name == "UserId") {
                $(this).find('input').val(guessedUserId);
            }
        }
    });

    div.toggle(params.length > 0);

    if (params.length > 0 && !allParamsHaveValues) {
        div.find('input:first').focus();
    }

    return allParamsHaveValues;
}

function forwardEvent(event, element) {
    if (event == "focus") {
        $(".CodeMirror-wrapping").addClass("focus");
    }
    if (event == "blur") {
        $(".CodeMirror-wrapping").removeClass("focus");
    }
}

$(function () {
    $("#grid").resize(function () {
        var width = 0;
        $(".slick-header-column").each(function () { width += $(this).outerWidth(); });
        $.data(this, "width", width)
    }).add(window).resize(function () {
        var width = $("#grid").data("width"), docWidth = document.documentElement.clientWidth - 80;
        if (width > docWidth) width = docWidth - 80;
        if (width < 950) width = 950;
        if (!showingGraph) {
               $("#queryResults").width(width + 20);
               $("#gridStats").width(width + 10);
        }
    });
});<commit_msg>allow for multiple series<commit_after>$.fn.tabs = function () {
    $(this).delegate("a:not(.youarehere)", "click", function () {
        if (this.id == "graphTabButton") {
            $("#gridStats").hide();
        } else {
            $("#gridStats").show();
        }
        $(this.hash).show();
        $(this).addClass("youarehere")
               .siblings(".youarehere")
               .removeClass("youarehere").each(function () {
                   $(this.hash).hide();
               });
    }).delegate("a", "click", function () {
        return false;
    });
};

var showingGraph = false;

function encodeColumn(s) {
    if (s != null && s.replace != null) {
        s = s.replace(/[\n\r]/g, " ")
              .replace(/&(?!\w+([;\s]|$))/g, "&")
              .replace(/</g, "<")
              .replace(/>/g, ">")
              .substring(0, 400);
        return s;
    } else {
        return s;
    }
}

function splitTags(s) {
    if (s == null) return [];
    var tmp = s.split("<");
    var rval = [];
    for (var i = 0; i < tmp.length; i++) {
        if (tmp[i] != "") {
            rval.push(tmp[i].replace(">", ""));
        }
    }

    return rval;
}

var current_results;

function scrollToResults() {
    var target_offset = $("#toolbar").offset();
    var target_top = target_offset.top - 10;
    $('html, body').animate({ scrollTop: target_top }, 500);
}

// this is from SO 901115
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

function populateParamsFromUrl() {
    $('#queryParams').find("p input").each(function () {
        var val = getParameterByName(this.name);
        if (val != null && val.length > 0) {
            $(this).val(getParameterByName(this.name));
        }
    });
}

function displayCaptcha() {
    $('form input[type=submit]').hide();
    $('#captcha').show();

    $("#recaptcha_response_field").keydown(function (key) {
        if (key.keyCode == 13) {
            $("#btn-captcha").click();
            return false;
        }
        return true;
    }).focus();

    var captcha = function () {
        $(this).unbind("click");
        $.ajax({
            url: '/captcha',
            data: $('#captcha').closest('form').serialize(),
            type: 'POST',
            success: function (data) {
                if (data.success) {
                    $('form input[type=submit]').show();
                    $('#captcha').hide();
                    $('#captcha').closest('form').submit();
                } else {
                    $("#captcha-error").fadeIn();
                    $("#btn-captcha").click(captcha);
                    var text = $("#recaptcha_response_field");
                    var once = function () { $("#captcha-error").fadeOut(); text.unbind("keydown", once) };
                    text.keydown(once);
                }
            },
            dataType: "json"
        });

    };

    $("#btn-captcha").click(captcha);
}

function isGraph(resultSet) {

    var graph = true;

    for (var i = 0; i < resultSet.columns.length; i++) {
        var type = resultSet.columns[i]["type"];
        if (i != 0 && type == 'Date') {
            graph = false;
            break;
        }
        if (type != 'Number' && type != 'Date') {
            graph = false;
            break;
        }
    }
    return graph;
}

function showTooltip(x, y, contents) {
    $('
' + contents + '<\/div>').css({
        position: 'absolute',
        display: 'none',
        top: y + 5,
        left: x + 5,
        border: '1px solid #fdd',
        padding: '2px',
        'background-color': '#fee',
        opacity: 0.80
    }).appendTo("body").fadeIn(200);
}

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function bindToolTip(graph, suffix) {
    var previousPoint = null;
    var lastCall = 0;
    graph.bind("plothover", function (event, pos, item) {

        var toolTip;

        if (item) {

            if (previousPoint == null || previousPoint[0] != item.datapoint[0] || previousPoint[1] != item.datapoint[1]) {
                previousPoint = item.datapoint;

                $("#tooltip").remove();
                var x = item.datapoint[0].toFixed(2),
                    y = item.datapoint[1].toFixed(2);

                showTooltip(item.pageX - 10, item.pageY - 40, addCommas(parseInt(y)) + suffix);
            }
        }
        else {
            if (previousPoint != null) {
                $("#tooltip").remove();
            }
            previousPoint = null;
        }

    });
}

function renderGraph(resultSet) {

    var options = {
        legend: { position: "nw" },
        grid: { hoverable: true },
        selection: { mode: "x" },
        series: { lines: { show: true }, points: { show: true} }
    };
    if (resultSet.columns[0]["type"] == 'Date') {
        options.xaxis = { mode: "time" };
    }
    var graph = $("#graph");

    var series = [];

    for (var col = 1; col < resultSet.columns.length; col++) {
        series.push([]);
    }

    for (var row = 0; row < resultSet.rows.length; row++) {
        for (var col = 1; col < resultSet.columns.length; col++) {
            series[col - 1].push([resultSet.rows[row][0], resultSet.rows[row][col]]);
        }
    }

    $.plot(graph, series, options);
    bindToolTip(graph, "");
}

function gotResults(results) {

    $(".loading").hide();
    $('form input[type=submit]').attr('disabled', null);

    if (results && results.captcha) {
        displayCaptcha();
        return;
    }

    current_results = results;

    if (results.resultSets && isGraph(results.resultSets[0])) {
        $('#graphTabButton').show();
        var width = document.documentElement.clientWidth;
        if (width < 950) { width = 950; }
        $("#graph").width(width - 90);
        $("#queryResults").width(width - 70);
        $("#gridStats").width(width - 80);
        showingGraph = true;
        renderGraph(results.resultSets[0]);
    }
    else {
        showingGraph = false;
        $('#graphTabButton').hide();
    }

    if (results.error != null) {
        $("#queryErrorBox").show();
        $("#queryError").html(results.error);
        return;
    }

    if (results.truncated == true) {
        $("#queryErrorBox").show();
        $("#queryError").html("Your query was truncated, only " + results.maxResults + " results are allowed");
    }

    $("#messages pre code").text(results.messages);

    var currentParams = "?";
    currentParams += $('#queryParams').find("p input").serialize();

    if (currentParams == "?") {
        currentParams = "";
    }

    $("#permalinks").show();
    var currentLink = $("#permalink")[0];

    var linkId = results.queryId;
    var slug = results.slug == null ? "/" : "/" + results.slug;
    var linkPath = results.textOnly ? "qt" : "q";
    if (window.queryId !== undefined) {
        linkId = queryId;
        slug = "/" + querySlug;
        linkPath = results.textOnly ? "st" : "s";
    }

    currentLink.href = "/" + results.siteName + "/"+ linkPath + "/" + linkId + slug + currentParams;

    $("#downloadCsv")[0].href = "/" + results.siteName + "/" + (results.excludeMetas ? "n" : "") + (results.multiSite ? "m" : "") + "csv/" + results.queryId + currentParams;

    $(".otherPermalink").each(function () {
        // slug
        this.href = this.href.substring(0, this.href.lastIndexOf("/"));
        // query id
        this.href = this.href.substring(0, this.href.lastIndexOf("/"));
        // type
        this.href = this.href.substring(0, this.href.lastIndexOf("/") + 1) + linkPath + "/" + linkId + slug;
    });

    $("#gridStats .duration").text("Duration: " + results.executionTime + "ms");

    if (results.executionPlan && results.executionPlan.length > 0) {
        $("#planTabButton").show();

        $("#executionPlan").html(results.executionPlan);
        QP.drawLines();

        $("#downloadPlan")[0].href = "/" + results.siteName + "/" + (results.excludeMetas ? "n" : "") + (results.multiSite ? "m" : "") + "plan/" + results.queryId + currentParams;
        $("#downloadPlan").show();
    }
    else {
        $("#planTabButton").hide();
        $("#downloadPlan").hide();
    }

    if (results.textOnly || results.resultSets.length == 0) {
        $("#messagesTabButton").click();
        $("#resultsTabButton").hide();

        $("#queryResults").show();
        return;
    }

    $("#resultsTabButton").show();
    $("#resultsTabButton").click();
    $("#grid").show();
    $("#messages").hide();

    var model = [];
    var maxWidths = [];

    for (var c = 0; c < results.resultSets[0].columns.length; c++) {
        model.push({
            width: 60,
            cssClass: (results.resultSets[0].columns[c].type == "Number" ? "number" : "text"),
            id: results.resultSets[0].columns[c].name,
            name: results.resultSets[0].columns[c].name,
            field: c
        });
        maxWidths.push(results.resultSets[0].columns[c].name.length);
    }

    var rows = [];
    var hasTags = false;

    for (var i = 0; i < results.resultSets[0].rows.length; i++) {
        var row = {};

        for (var c = 0; c < results.resultSets[0].columns.length; c++) {
            var data = null;
            var col = results.resultSets[0].rows[i][c];
            if (col != null && col.title != null && col.id != null) {
                var specialType = results.resultSets[0].columns[c].type;
                var baseUrl;
                switch (specialType) {
                    case "User":
                        baseUrl = "/users/";
                        break;
                    case "Post":
                        baseUrl = "/questions/"
                        break;
                    case "SuggestedEdit":
                        baseUrl = "/suggested-edits/"
                        break;
                    default:
                        baseUrl = "invalid";
                }

                data = ("" + encodeColumn(col.title) + "");
                if (col.title.length > maxWidths[c]) maxWidths[c] = col.title.length;
            } else if (model[c].field == "Tags" || model[c].field == "TagName") {
                // smart rendering of tags
                var tags = splitTags(col);
                var tmpLength = tags.join(" ").length;
                if (col != null && tmpLength > maxWidths[c]) maxWidths[c] = tmpLength;
                for (var tagIndex = 0; tagIndex < tags.length; tagIndex++) {
                    tags[tagIndex] = "" + tags[tagIndex] + "";
                };
                data = tags.join(" ");
                hasTags = true;
            } else {
                if (results.resultSets[0].columns[c]["type"] == "Date") {
                    data = (new Date(col)).toString("yyyy-MM-dd HH:mm:ss");
                } else {
                    data = (encodeColumn(col));
                }
                if (data != null && data.toString().length > maxWidths[c]) maxWidths[c] = data.toString().length;
            }
            row[c] = data;
        }
        rows.push(row);
    }

    for (var i = 0; i < model.length; i++) {
        model[i].width = maxWidths[i] * 12 > 250 ? 300 : 8 + maxWidths[i] * 12;
    }

    $("#queryResults").show();
    $("#gridStats .rows").text("" + rows.length + " row" + (rows.length == 1 ? "" : "s"));

    var options = {
        enableCellNavigation: false,
        enableColumnReorder: false,
        rowHeight: hasTags ? 35 : 25
    };

    var grid = new Slick.Grid($("#grid"), rows, model, options);
    grid.onColumnsResized = function () { $("#grid").resize() };

    scrollToResults();

    $("#queryResults").insertAfter('.page:first').css({ 'padding': '0 30px', 'margin': '0 auto' });
    $("#grid").resize();
}

function executeQuery(sql) {
    $("#permalinks, #queryResults, #queryErrorBox").hide();

    if (!ensureAllParamsEntered(sql)) {
        return false;
    }

    $(".loading").show();
    $('#runQueryForm input[type=submit]', this).attr('disabled', 'disabled');

    $.ajax({
      cache: false,
      url: $('#runQueryForm')[0].action,
      type: "POST",
      data: $("#runQueryForm").serialize(),
      error: function () {
        alert("Something is wrong with the server!");
      },
      success: gotResults
    });

    return false;
}

function ensureAllParamsEntered(query) {
    var pattern = /##([a-zA-Z0-9]+):?([a-zA-Z]+)?##/g;
    var params = query.match(pattern);
    if (params == null) params = [];

    var div = $('#queryParams');

    var allParamsHaveValues = true;

    for (var i = 0; i < params.length; i++) {
        params[i] = params[i].substring(2, params[i].length - 2);
        var colonPos = params[i].indexOf(":");
        if (colonPos > 0) {
            params[i] = params[i].substring(0, colonPos);
        }

        var currentParam = div.find("input[name=" + params[i] + "]");
        if (currentParam.length == 0) {
            div.append("
" + params[i] + "\n" +
            "<input type=\"text\" name=\"" + params[i] + "\" value=\"\" />

");
            allParamsHaveValues = false;
        } else {
            if (currentParam.val().length == 0) {
                allParamsHaveValues = false;
            }
        }
    }

    // remove extra params
    div.children("p").each(function () {
        var name = $(this).find('input').attr('name');
        var found = false;
        for (var i = 0; i < params.length; i++) {
            found = params[i] == name;
            if (found) break;
        }
        if (!found) {
            $(this).remove();
        } else {
            // auto param
            if ($(this).find('input').val().length == 0 && name == "UserId") {
                $(this).find('input').val(guessedUserId);
            }
        }
    });

    div.toggle(params.length > 0);

    if (params.length > 0 && !allParamsHaveValues) {
        div.find('input:first').focus();
    }

    return allParamsHaveValues;
}

function forwardEvent(event, element) {
    if (event == "focus") {
        $(".CodeMirror-wrapping").addClass("focus");
    }
    if (event == "blur") {
        $(".CodeMirror-wrapping").removeClass("focus");
    }
}

$(function () {
    $("#grid").resize(function () {
        var width = 0;
        $(".slick-header-column").each(function () { width += $(this).outerWidth(); });
        $.data(this, "width", width)
    }).add(window).resize(function () {
        var width = $("#grid").data("width"), docWidth = document.documentElement.clientWidth - 80;
        if (width > docWidth) width = docWidth - 80;
        if (width < 950) width = 950;
        if (!showingGraph) {
               $("#queryResults").width(width + 20);
               $("#gridStats").width(width + 10);
        }
    });
});<|endoftext|>


<commit_before>const models = require('../models');

const muddleCtrl = module.exports = {};

muddleCtrl.create = function (req, res) {
  models.Muddle.create(req.body)
    .then(function () {
      res.redirect('/readAll');
    });
};

muddleCtrl.list = function (req, res) {
  models.Muddle.findAll({
    order: [['createdAt', 'DESC']]
  })
    .then(function (muddles) {
      console.log('muddles:', muddles);
      Object.assign(res.locals, {
        title: 'readAll',
        subtitle: 'The list of the things that we messed up.',
        muddles,
      });
      return muddles.getUsers();
    })
    .then(function (users) {
      console.log('users', users);
      res.render('muddles');
    });
};

muddleCtrl.read = function (req, res) {
  models.Muddle.findOne({
    where: { id: req.params.muddleId }
  })
    .then(function (muddle) {
      Object.assign(res.locals, {
        title: 'readOne',
        subtitle: 'The one of the things that we messed up.',
        muddle,
      });
      return muddle.getUser();
    })
    .then(function (user) {
      if (user) {
        Object.assign(res.locals, {
          author: user.username,
          authorLink: user.profile,
        });
      } else {
        Object.assign(res.locals, {
          anon: true,
        });
      }
      res.render('muddle');
    });
};
<commit_msg>try singular<commit_after>const models = require('../models');

const muddleCtrl = module.exports = {};

muddleCtrl.create = function (req, res) {
  models.Muddle.create(req.body)
    .then(function () {
      res.redirect('/readAll');
    });
};

muddleCtrl.list = function (req, res) {
  models.Muddle.findAll({
    order: [['createdAt', 'DESC']]
  })
    .then(function (muddles) {
      console.log('muddles:', muddles);
      Object.assign(res.locals, {
        title: 'readAll',
        subtitle: 'The list of the things that we messed up.',
        muddles,
      });
      return muddles.getUser();
    })
    .then(function (users) {
      console.log('users', users);
      res.render('muddles');
    });
};

muddleCtrl.read = function (req, res) {
  models.Muddle.findOne({
    where: { id: req.params.muddleId }
  })
    .then(function (muddle) {
      Object.assign(res.locals, {
        title: 'readOne',
        subtitle: 'The one of the things that we messed up.',
        muddle,
      });
      return muddle.getUser();
    })
    .then(function (user) {
      if (user) {
        Object.assign(res.locals, {
          author: user.username,
          authorLink: user.profile,
        });
      } else {
        Object.assign(res.locals, {
          anon: true,
        });
      }
      res.render('muddle');
    });
};
<|endoftext|>


<commit_before>(function () {
    'use strict';

    /**
     *
     * @ngdoc component
     * @author vpellegrino
     * @name app.components.loadingAnimation
     * @description
     * A component used to wrap whatever HTML content with a loading message above animated dots, while a promise is still in progress
     *
     * @example
     *
     *

     *  <loading-animation message="Loading">Loaded content</loading-animation>
     *

     *
     */
    angular.module('app.components')
        .component('loadingAnimation', {
            transclude: true,
            bindings: {
                message:'@?',   // message to be displayed during loading
                messageKey: '@?',   // message key to be resolved to display the related message
                promise: '<'    // while this promise is not yet resolved, a dotted animation will be displayed
            },
            templateUrl: "loadingAnimation.html",
            controller: ['$filter', '$q', function ($filter, $q) {
                var $ctrl = this;
                // init phase
                if ($ctrl.messageKey && angular.isString($ctrl.messageKey)) {
                    $ctrl.message = $filter('translate')($ctrl.messageKey);
                }
                // lifecycle hooks
                $ctrl.$onChanges = function (changed) {
                    $ctrl.promiseSolved = false;
                    if(changed.promise) {
                        // if promise is changed, e.g. re-initialized, observing its status
                        $ctrl.promise = $q.when(changed.promise.currentValue);
                        $ctrl.promise.then(function () {
                            // promise was resolved with success
                            $ctrl.promiseSolved = true;
                        }, function() {
                            // promise was resolved with error
                            $ctrl.promiseSolved = true;
                        });
                    }
                };
            }]
        });
})();
<commit_msg>Update loadingAnimation.component.js<commit_after>(function () {
    'use strict';

    /**
     *
     * @ngdoc component
     * @author vpellegrino
     * @name app.components.loadingAnimation
     * @description
     * A component used to wrap whatever HTML content with a loading message above animated dots, while a promise is still in progress
     *
     * @example
     *
     *

     *  <loading-animation promise="api.promise" message="Loading">Loaded content</loading-animation>
     *

     *
     */
    angular.module('app.components')
        .component('loadingAnimation', {
            transclude: true,
            bindings: {
                message:'@?',   // message to be displayed during loading
                messageKey: '@?',   // message key to be resolved to display the related message
                promise: '<'    // while this promise is not yet resolved, a dotted animation will be displayed
            },
            templateUrl: "loadingAnimation.html",
            controller: ['$filter', '$q', function ($filter, $q) {
                var $ctrl = this;
                // init phase
                if ($ctrl.messageKey && angular.isString($ctrl.messageKey)) {
                    $ctrl.message = $filter('translate')($ctrl.messageKey);
                }
                // lifecycle hooks
                $ctrl.$onChanges = function (changed) {
                    $ctrl.promiseSolved = false;
                    if(changed.promise) {
                        // if promise is changed, e.g. re-initialized, observing its status
                        $ctrl.promise = $q.when(changed.promise.currentValue);
                        $ctrl.promise.then(function () {
                            // promise was resolved with success
                            $ctrl.promiseSolved = true;
                        }, function() {
                            // promise was resolved with error
                            $ctrl.promiseSolved = true;
                        });
                    }
                };
            }]
        });
})();
<|endoftext|>


<commit_before>import "./markspeciallinks";
import $ from "jquery";
import registry from "@patternslib/patternslib/src/core/registry";
import utils from "@patternslib/patternslib/src/core/utils";

    /* ==========================
   TEST: MarkSpecialLinks
  ========================== */

    describe("MarkSpecialLinks", function () {

        beforeEach(function () {
            this.$el = $(
                "" +
                    '
' +
                    '
Find out What&#39s new in Plone.
' +
                    '     Plone is written in Python.' +
                    "
" +
                    "
" +
                    '
' +
                    '
Find out What&#39s new in Plone.
' +
                    '     Plone is written in Python.' +
                    "
" +
                    "
" +
                    '
' +
                    '
Find out What&#39s new in Plone.
' +
                    '     Plone is written in Python.' +
                    "
" +
                    "
" +
                    '
' +
                    "
" +
                    '
http
' +
                    '
https
' +
                    '
mailto
' +
                    '
ftp
' +
                    '
news
' +
                    '
irc
' +
                    '
h323
' +
                    '
sip
' +
                    '
callto
' +
                    '
feed
' +
                    '
webcal
' +
                    "
" +
                    "
" +
                    '
' +
                    '
Find out What&#39s new in Plone.
' +
                    '     Plone is written in Python.' +
                    "
" +
                    "
"
            );
            // const url = "https://www.plone.org/";
            // location = window.location;
            // const mockLocation = new URL(url);
            // mockLocation.replace = jest.fn();
            // delete window.location;
            // window.location = mockLocation;
        });
        it("normal external links have target=_blank", async function () {
            const util = require('util');
            await utils.timeout(1);
            registry.scan(this.$el);
            await utils.timeout(1);
            var link = this.$el.find("a");
            // expect(window.location.url).toEqual(url);
            expect(link.eq(0).attr("target") === undefined).toEqual(true);
            expect(link.eq(1).attr("target") === undefined).toEqual(true);
            expect(link.eq(2).attr("target")).toEqual("_blank");
            expect(link.eq(3).attr("target") === undefined).toEqual(true);
            expect(link.eq(0).prev()[0].tagName).toEqual("I");
            expect(link.eq(1).prev()[0].tagName).not.toEqual("I");
            expect(link.eq(4).prev().length).toEqual(0);
            expect(link.eq(5).prev()[0].tagName).not.toEqual("I");
        });
        it("check for correct icon classes per protocol", function () {
            registry.scan(this.$el);
            var listel = this.$el.next(".icons").find("li");
            expect(listel.eq(0).find("i").hasClass("link-external")).toEqual(true);
            expect(listel.eq(1).find("i").hasClass("link-https")).toEqual(true);
            expect(listel.eq(2).find("i").hasClass("link-mailto")).toEqual(true);
            expect(listel.eq(3).find("i").hasClass("link-ftp")).toEqual(true);
            expect(listel.eq(4).find("i").hasClass("link-news")).toEqual(true);
            expect(listel.eq(5).find("i").hasClass("link-irc")).toEqual(true);
            expect(listel.eq(6).find("i").hasClass("link-h323")).toEqual(true);
            expect(listel.eq(7).find("i").hasClass("link-sip")).toEqual(true);
            expect(listel.eq(8).find("i").hasClass("link-callto")).toEqual(true);
            expect(listel.eq(9).find("i").hasClass("link-feed")).toEqual(true);
            expect(listel.eq(10).find("i").hasClass("link-webcal")).toEqual(true);
        });
        it("do not show the lock icon for anchor links", function () {
            registry.scan(this.$el);
            var link = this.$el.next(".anchors").find("p").find("a");
            expect(link.eq(0).prev().length).toEqual(0);
        });
    });
<commit_msg>Code formatting.<commit_after>import "./markspeciallinks";
import $ from "jquery";
import registry from "@patternslib/patternslib/src/core/registry";
import utils from "@patternslib/patternslib/src/core/utils";

/* ==========================
   TEST: MarkSpecialLinks
  ========================== */

describe("MarkSpecialLinks", function () {
    beforeEach(function () {
        this.$el = $(
            "" +
                '
' +
                '
Find out What&#39s new in Plone.
' +
                '     Plone is written in Python.' +
                "
" +
                "
" +
                '
' +
                '
Find out What&#39s new in Plone.
' +
                '     Plone is written in Python.' +
                "
" +
                "
" +
                '
' +
                '
Find out What&#39s new in Plone.
' +
                '     Plone is written in Python.' +
                "
" +
                "
" +
                '
' +
                "
" +
                '
http
' +
                '
https
' +
                '
mailto
' +
                '
ftp
' +
                '
news
' +
                '
irc
' +
                '
h323
' +
                '
sip
' +
                '
callto
' +
                '
feed
' +
                '
webcal
' +
                "
" +
                "
" +
                '
' +
                '
Find out What&#39s new in Plone.
' +
                '     Plone is written in Python.' +
                "
" +
                "
"
        );
        // const url = "https://www.plone.org/";
        // location = window.location;
        // const mockLocation = new URL(url);
        // mockLocation.replace = jest.fn();
        // delete window.location;
        // window.location = mockLocation;
    });
    it("normal external links have target=_blank", async function () {
        const util = require("util");
        await utils.timeout(1);
        registry.scan(this.$el);
        await utils.timeout(1);
        var link = this.$el.find("a");
        // expect(window.location.url).toEqual(url);
        expect(link.eq(0).attr("target") === undefined).toEqual(true);
        expect(link.eq(1).attr("target") === undefined).toEqual(true);
        expect(link.eq(2).attr("target")).toEqual("_blank");
        expect(link.eq(3).attr("target") === undefined).toEqual(true);
        expect(link.eq(0).prev()[0].tagName).toEqual("I");
        expect(link.eq(1).prev()[0].tagName).not.toEqual("I");
        expect(link.eq(4).prev().length).toEqual(0);
        expect(link.eq(5).prev()[0].tagName).not.toEqual("I");
    });
    it("check for correct icon classes per protocol", function () {
        registry.scan(this.$el);
        var listel = this.$el.next(".icons").find("li");
        expect(listel.eq(0).find("i").hasClass("link-external")).toEqual(true);
        expect(listel.eq(1).find("i").hasClass("link-https")).toEqual(true);
        expect(listel.eq(2).find("i").hasClass("link-mailto")).toEqual(true);
        expect(listel.eq(3).find("i").hasClass("link-ftp")).toEqual(true);
        expect(listel.eq(4).find("i").hasClass("link-news")).toEqual(true);
        expect(listel.eq(5).find("i").hasClass("link-irc")).toEqual(true);
        expect(listel.eq(6).find("i").hasClass("link-h323")).toEqual(true);
        expect(listel.eq(7).find("i").hasClass("link-sip")).toEqual(true);
        expect(listel.eq(8).find("i").hasClass("link-callto")).toEqual(true);
        expect(listel.eq(9).find("i").hasClass("link-feed")).toEqual(true);
        expect(listel.eq(10).find("i").hasClass("link-webcal")).toEqual(true);
    });
    it("do not show the lock icon for anchor links", function () {
        registry.scan(this.$el);
        var link = this.$el.next(".anchors").find("p").find("a");
        expect(link.eq(0).prev().length).toEqual(0);
    });
});
<|endoftext|>


<commit_before>import "./passwordstrength";
import $ from "jquery";
import registry from "@patternslib/patternslib/src/core/registry";
import utils from "@patternslib/patternslib/src/core/utils";

// window.mocha.setup("bdd");
// $.fx.off = true;

/* ==========================
TEST: Password strength
========================== */

describe("Password strength", function () {

function fakeZxcvbn(input, strings) {
    window.providedStrings = strings;
    return {
	score: Math.min(input.length, 4),
    };
}

function getScripts() {
    return [].map
	.call(document.getElementsByTagName("script"), function (s) {
	    return s.src;
	})
	.filter(function (src) {
	    return src.indexOf("zxcvbn") !== -1;
	});
}

it("adds markup below input element", function () {
    var $el = $(
	'
<input type="password" class="pat-passwordstrength" />
'
    );
    window.zxcvbn = fakeZxcvbn;
    registry.scan($el);

    expect($el.find(".progress").length).toEqual(1);
    expect($el.find(".progress-bar").length).toEqual(1);
});

it("tries to load zxcvbn once if not available", function () {
    var $el2,
	$el = $(
	    '
<input type="password" class="pat-passwordstrength" data-pat-passwordstrength="zxcvbn: http://example.com/zxcvbn.js" />
'
	);
    window.zxcvbn = undefined;
    expect(getScripts().length).toEqual(0);
    registry.scan($el);
    expect(getScripts().length).toEqual(1);
    expect(getScripts()).toContain("http://example.com/zxcvbn.js");

    $el2 = $(
	'
<input type="password" class="pat-passwordstrength" data-pat-passwordstrength="zxcvbn: http://example.com/zxcvbn.js" />
'
    );
    registry.scan($el2);
    expect(getScripts().length).toEqual(1);
    expect(getScripts()).toContain("http://example.com/zxcvbn.js");
});

it("sets level based on the entered password", function () {
    var $el = $(
	'
<input type="password" class="pat-passwordstrength" />
'
    );
    window.zxcvbn = fakeZxcvbn;
    registry.scan($el);

    $el.find("input[type=password]").attr("value", "a").trigger("keyup");
    expect($el.find(".progress-bar").attr("class")).toEqual(
	"progress-bar w-25 bg-danger"
    );
    expect(window.providedStrings.length).toEqual(0);

    $el.find("input[type=password]").attr("value", "aa").trigger("keyup");
    expect($el.find(".progress-bar").attr("class")).toEqual(
	"progress-bar w-50 bg-warning"
    );
    expect(window.providedStrings.length).toEqual(0);

    $el.find("input[type=password]").attr("value", "aaa").trigger("keyup");
    expect($el.find(".progress-bar").attr("class")).toEqual(
	"progress-bar w-75 bg-warning"
    );
    expect(window.providedStrings.length).toEqual(0);

    $el.find("input[type=password]").attr("value", "aaaa").trigger("keyup");
    expect($el.find(".progress-bar").attr("class")).toEqual(
	"progress-bar w-100 bg-success"
    );
    expect(window.providedStrings.length).toEqual(0);
});

it("provides zxcvbn with other form field values", function () {
    var $el = $(
	"<form>" +
	    '<input type="input" name="username" value="bob_geldof" />' +
	    '<input type="password" class="pat-passwordstrength" />' +
	    '<input type="checkbox" name="spam_me" checked="yes">' +
	    "</form>"
    );
    window.zxcvbn = fakeZxcvbn;
    registry.scan($el);

    $el.find("input[type=password]").attr("value", "a").trigger("keyup");
    expect($el.find(".progress-bar").attr("class")).toEqual(
	"progress-bar w-25 bg-danger"
    );
    expect(window.providedStrings.length).toEqual(2);
    expect(window.providedStrings).toContain("bob_geldof");
    expect(window.providedStrings).toContain("on");
});
});
<commit_msg>cleanup<commit_after>import "./passwordstrength";
import $ from "jquery";
import registry from "@patternslib/patternslib/src/core/registry";

/* ==========================
TEST: Password strength
========================== */

describe("Password strength", function () {

function fakeZxcvbn(input, strings) {
    window.providedStrings = strings;
    return {
	score: Math.min(input.length, 4),
    };
}

function getScripts() {
    return [].map
	.call(document.getElementsByTagName("script"), function (s) {
	    return s.src;
	})
	.filter(function (src) {
	    return src.indexOf("zxcvbn") !== -1;
	});
}

it("adds markup below input element", function () {
    var $el = $(
	'
<input type="password" class="pat-passwordstrength" />
'
    );
    window.zxcvbn = fakeZxcvbn;
    registry.scan($el);

    expect($el.find(".progress").length).toEqual(1);
    expect($el.find(".progress-bar").length).toEqual(1);
});

it("tries to load zxcvbn once if not available", function () {
    var $el2,
	$el = $(
	    '
<input type="password" class="pat-passwordstrength" data-pat-passwordstrength="zxcvbn: http://example.com/zxcvbn.js" />
'
	);
    window.zxcvbn = undefined;
    expect(getScripts().length).toEqual(0);
    registry.scan($el);
    expect(getScripts().length).toEqual(1);
    expect(getScripts()).toContain("http://example.com/zxcvbn.js");

    $el2 = $(
	'
<input type="password" class="pat-passwordstrength" data-pat-passwordstrength="zxcvbn: http://example.com/zxcvbn.js" />
'
    );
    registry.scan($el2);
    expect(getScripts().length).toEqual(1);
    expect(getScripts()).toContain("http://example.com/zxcvbn.js");
});

it("sets level based on the entered password", function () {
    var $el = $(
	'
<input type="password" class="pat-passwordstrength" />
'
    );
    window.zxcvbn = fakeZxcvbn;
    registry.scan($el);

    $el.find("input[type=password]").attr("value", "a").trigger("keyup");
    expect($el.find(".progress-bar").attr("class")).toEqual(
	"progress-bar w-25 bg-danger"
    );
    expect(window.providedStrings.length).toEqual(0);

    $el.find("input[type=password]").attr("value", "aa").trigger("keyup");
    expect($el.find(".progress-bar").attr("class")).toEqual(
	"progress-bar w-50 bg-warning"
    );
    expect(window.providedStrings.length).toEqual(0);

    $el.find("input[type=password]").attr("value", "aaa").trigger("keyup");
    expect($el.find(".progress-bar").attr("class")).toEqual(
	"progress-bar w-75 bg-warning"
    );
    expect(window.providedStrings.length).toEqual(0);

    $el.find("input[type=password]").attr("value", "aaaa").trigger("keyup");
    expect($el.find(".progress-bar").attr("class")).toEqual(
	"progress-bar w-100 bg-success"
    );
    expect(window.providedStrings.length).toEqual(0);
});

it("provides zxcvbn with other form field values", function () {
    var $el = $(
	"<form>" +
	    '<input type="input" name="username" value="bob_geldof" />' +
	    '<input type="password" class="pat-passwordstrength" />' +
	    '<input type="checkbox" name="spam_me" checked="yes">' +
	    "</form>"
    );
    window.zxcvbn = fakeZxcvbn;
    registry.scan($el);

    $el.find("input[type=password]").attr("value", "a").trigger("keyup");
    expect($el.find(".progress-bar").attr("class")).toEqual(
	"progress-bar w-25 bg-danger"
    );
    expect(window.providedStrings.length).toEqual(2);
    expect(window.providedStrings).toContain("bob_geldof");
    expect(window.providedStrings).toContain("on");
});
});
<|endoftext|>


<commit_before>angular.module('orderCloud')
    .controller('OrderShipmentsCtrl', OrderShipmentsController)
;

function OrderShipmentsController($stateParams, OrderShipments) {
    var vm = this;
    vm.list = OrderShipments;
    vm.orderID = $stateParams.orderid;

    vm.pageChanged = function() {
        ocOrderShipmentsService.List($stateParams.orderid, vm.list.Meta.Page, vm.list.Meta.PageSize)
            .then(function(data) {
                vm.list = data;
            });
    };

    vm.loadMore = function() {
        vm.list.Meta.Page++;
        ocOrderShipmentsService.List($stateParams.orderid, vm.list.Meta.Page, vm.list.Meta.PageSize)
            .then(function(data) {
                vm.list.Items = vm.list.Items.concat(data.Items);
                vm.list.Meta = data.Meta;
            });
    };

    vm.selectShipment = function(shipment) {
        vm.selectedShipment = angular.copy(shipment);
    };
    if (vm.list.Items.length) vm.selectShipment(vm.list.Items[0]);
}<commit_msg>Adding OrderLineItems to controller calls to list ShipmentItems<commit_after>angular.module('orderCloud')
    .controller('OrderShipmentsCtrl', OrderShipmentsController)
;

function OrderShipmentsController($stateParams, OrderShipments, OrderLineItems) {
    var vm = this;
    vm.list = OrderShipments;
    vm.orderID = $stateParams.orderid;

    vm.pageChanged = function() {
        ocOrderShipmentsService.List($stateParams.orderid, vm.list.Meta.Page, vm.list.Meta.PageSize, OrderLineItems)
            .then(function(data) {
                vm.list = data;
            });
    };

    vm.loadMore = function() {
        vm.list.Meta.Page++;
        ocOrderShipmentsService.List($stateParams.orderid, vm.list.Meta.Page, vm.list.Meta.PageSize, OrderLineItems)
            .then(function(data) {
                vm.list.Items = vm.list.Items.concat(data.Items);
                vm.list.Meta = data.Meta;
            });
    };

    vm.selectShipment = function(shipment) {
        vm.selectedShipment = angular.copy(shipment);
    };
    if (vm.list.Items.length) vm.selectShipment(vm.list.Items[0]);
}<|endoftext|>


<commit_before>import * as utils from '../../utils';
import helper from '../helper';
import settings from '../../settings';
import m from 'mithril';
import clockSettings from './clockSettings';

export default function controller() {
  let clockInterval = null;
  let clockMap = null;
  const isRunning = m.prop(false);
  const clockObj = m.prop();

  function reload() {
    clockMap = {
      'simple': simpleClock.bind(undefined, settings.clock.simple.time()),
      'increment': incrementClock.bind(undefined, settings.clock.increment.time(), settings.clock.increment.increment()),
      'delay': delayClock.bind(undefined, settings.clock.delay.time(), settings.clock.delay.increment())
    };
    isRunning(false);
    clockObj(clockMap[settings.clock.clockType()]());
  }

  reload();

  const clcokSettingsCtrl = clockSettings.controller();

  function clockTap (side) {
    clockObj().clockHit(side);
    if (clockInterval) {
      clearInterval(clockInterval);
    }
    clockInterval = setInterval(clockObj().tick, 1000);
  }

  function startStop () {
    if (isRunning()) {
      isRunning(false);
      clearInterval(clockInterval);
    }
    else {
      isRunning(true);
      clockInterval = setInterval(clockObj().tick, 1000);
    }
  }

  window.plugins.insomnia.keepAwake();

  return {
    isRunning,
    startStop,
    clcokSettingsCtrl,
    clockObj,
    reload,
    clockTap,
    onunload: () => {
      window.plugins.insomnia.allowSleepAgain();
      window.StatusBar.show();
      if (clockInterval) {
        clearInterval(clockInterval);
      }
    }
  };
}

function simpleClock(time) {
  const topTime = m.prop(time);
  const bottomTime = m.prop(time);
  const activeSide = m.prop(null);

  function tick () {
    if (activeSide() === 'top') {
      topTime(Math.max(topTime()-1, 0));
    }
    else if (activeSide() === 'bottom') {
      bottomTime(Math.max(bottomTime()-1, 0));
    }
    m.redraw();
  }

  function isFlagged () {
    if (topTime() <= 0) {
      return 'top';
    }
    else if (bottomTime() <= 0) {
      return 'bottom';
    }
    return null;
  }

  function clockHit (side) {
    if (activeSide() === 'top') {
      if (side === activeSide()) {
        activeSide('bottom');
      }
    }
    else if (activeSide() === 'bottom') {
      if (side === activeSide()) {
        activeSide('top');
      }
    }
    else {
      if (side === 'top') {
        activeSide('bottom');
      }
      else {
        activeSide('top');
      }
    }
  }

  return {
    topTime: topTime,
    bottomTime: bottomTime,
    activeSide: activeSide,
    tick: tick,
    isFlagged: isFlagged,
    clockHit: clockHit
  };
}

function incrementClock() {

}

function delayClock() {

}
<commit_msg>Refactor no-increment clock to just be a special case of an increment clock<commit_after>import * as utils from '../../utils';
import helper from '../helper';
import settings from '../../settings';
import m from 'mithril';
import clockSettings from './clockSettings';

export default function controller() {
  let clockInterval = null;
  let clockMap = null;
  const isRunning = m.prop(false);
  const clockObj = m.prop();

  function reload() {
    clockMap = {
      'simple': simpleClock.bind(undefined, settings.clock.simple.time()),
      'increment': incrementClock.bind(undefined, settings.clock.increment.time(), settings.clock.increment.increment()),
      'delay': delayClock.bind(undefined, settings.clock.delay.time(), settings.clock.delay.increment())
    };
    isRunning(false);
    clockObj(clockMap[settings.clock.clockType()]());
  }

  reload();

  const clcokSettingsCtrl = clockSettings.controller();

  function clockTap (side) {
    clockObj().clockHit(side);
    if (clockInterval) {
      clearInterval(clockInterval);
    }
    clockInterval = setInterval(clockObj().tick, 1000);
    isRunning(true);
  }

  function startStop () {
    if (isRunning()) {
      isRunning(false);
      clearInterval(clockInterval);
    }
    else {
      isRunning(true);
      clockInterval = setInterval(clockObj().tick, 1000);
    }
  }

  window.plugins.insomnia.keepAwake();

  return {
    isRunning,
    startStop,
    clcokSettingsCtrl,
    clockObj,
    reload,
    clockTap,
    onunload: () => {
      window.plugins.insomnia.allowSleepAgain();
      window.StatusBar.show();
      if (clockInterval) {
        clearInterval(clockInterval);
      }
    }
  };
}

function simpleClock(time) {
  return incrementClock(time, 0);
}

function incrementClock(time, increment) {
  const topTime = m.prop(time);
  const bottomTime = m.prop(time);
  const activeSide = m.prop(null);

  function tick () {
    if (activeSide() === 'top') {
      topTime(Math.max(topTime()-1, 0));
    }
    else if (activeSide() === 'bottom') {
      bottomTime(Math.max(bottomTime()-1, 0));
    }
    m.redraw();
  }

  function isFlagged () {
    if (topTime() <= 0) {
      return 'top';
    }
    else if (bottomTime() <= 0) {
      return 'bottom';
    }
    return null;
  }

  function clockHit (side) {
    if (activeSide() === 'top') {
      if (side === activeSide()) {
        activeSide('bottom');
        topTime(topTime() + increment);
      }
    }
    else if (activeSide() === 'bottom') {
      if (side === activeSide()) {
        activeSide('top');
        bottomTime(bottomTime() + increment);
      }
    }
    else {
      if (side === 'top') {
        activeSide('bottom');
      }
      else {
        activeSide('top');
      }
    }
  }

  return {
    topTime: topTime,
    bottomTime: bottomTime,
    activeSide: activeSide,
    tick: tick,
    isFlagged: isFlagged,
    clockHit: clockHit
  };
}

function delayClock() {

}
<|endoftext|>


<commit_before>(function() {
  'use strict';

  var app = angular.module('radar.patients.diagnoses');

  app.directive('diagnosisSelector', ['store', '_', function(store, _) {
    return {
      require: 'ngModel',
      templateUrl: 'app/patients/diagnoses/diagnosis-selector.html',
      scope: {
        'patient': '='
      },
      link: function(scope, element, attrs, ngModel) {
        scope.group = null;
        scope.groups = [];
        scope.diagnosis = null;
        scope.diagnoses = {};
        scope.loading = true;

        ngModel.$render = function() {
          scope.diagnosis = ngModel.$viewValue;
        };

        scope.getDiagnoses = function(group) {
          var key = group === null ? null : group.id;

          return scope.diagnoses[key] || [];
        };

        scope.setGroup = function(group) {
          scope.group = group;
        };

        scope.isActive = function(group) {
          return scope.group === group;
        };

        scope.use = function(diagnosis) {
          update(diagnosis);
        };

        scope.drop = function() {
          update(null);
        };

        function update(diagnosis) {
          scope.diagnosis = diagnosis;
          ngModel.$setViewValue(diagnosis);
        }

        // Load diagnoses
        store.findMany('diagnoses').then(function(diagnoses) {
          // Sort diagnoses by name
          diagnoses = _.sortBy(diagnoses, 'name');

          // Add a diagnosis
          function add(group, diagnosis) {
            var key = group === null ? null : group.id;

            if (scope.diagnoses[key] === undefined) {
              scope.diagnoses[key] = [];
            }

            scope.diagnoses[key].push(diagnosis);
          }

          _.forEach(diagnoses, function(diagnosis) {
            // Add diagnosis to all
            add(null, diagnosis);

            _.forEach(diagnosis.groups, function(group) {
              // Add diagnosis to group
              add(group.group, diagnosis);
            });
          });

          // Get's patients groups sorted by name
          scope.groups = _.sortBy(scope.patient.getGroups(), 'shortName')

          // Remove groups that don't have any diagnoses
          scope.groups = _.filter(scope.groups, function(group) {
            return scope.getDiagnoses(group).length > 0;
          });

          // Default to first group with diagnoses (otherwise all)
          if (scope.groups.length > 0) {
            scope.setGroup(scope.groups[0]);
          }

          // Finished loading
          scope.loading = false;
        });
      }
    };
  }]);
})();
<commit_msg>Add semicolon<commit_after>(function() {
  'use strict';

  var app = angular.module('radar.patients.diagnoses');

  app.directive('diagnosisSelector', ['store', '_', function(store, _) {
    return {
      require: 'ngModel',
      templateUrl: 'app/patients/diagnoses/diagnosis-selector.html',
      scope: {
        'patient': '='
      },
      link: function(scope, element, attrs, ngModel) {
        scope.group = null;
        scope.groups = [];
        scope.diagnosis = null;
        scope.diagnoses = {};
        scope.loading = true;

        ngModel.$render = function() {
          scope.diagnosis = ngModel.$viewValue;
        };

        scope.getDiagnoses = function(group) {
          var key = group === null ? null : group.id;

          return scope.diagnoses[key] || [];
        };

        scope.setGroup = function(group) {
          scope.group = group;
        };

        scope.isActive = function(group) {
          return scope.group === group;
        };

        scope.use = function(diagnosis) {
          update(diagnosis);
        };

        scope.drop = function() {
          update(null);
        };

        function update(diagnosis) {
          scope.diagnosis = diagnosis;
          ngModel.$setViewValue(diagnosis);
        }

        // Load diagnoses
        store.findMany('diagnoses').then(function(diagnoses) {
          // Sort diagnoses by name
          diagnoses = _.sortBy(diagnoses, 'name');

          // Add a diagnosis
          function add(group, diagnosis) {
            var key = group === null ? null : group.id;

            if (scope.diagnoses[key] === undefined) {
              scope.diagnoses[key] = [];
            }

            scope.diagnoses[key].push(diagnosis);
          }

          _.forEach(diagnoses, function(diagnosis) {
            // Add diagnosis to all
            add(null, diagnosis);

            _.forEach(diagnosis.groups, function(group) {
              // Add diagnosis to group
              add(group.group, diagnosis);
            });
          });

          // Get's patients groups sorted by name
          scope.groups = _.sortBy(scope.patient.getGroups(), 'shortName');

          // Remove groups that don't have any diagnoses
          scope.groups = _.filter(scope.groups, function(group) {
            return scope.getDiagnoses(group).length > 0;
          });

          // Default to first group with diagnoses (otherwise all)
          if (scope.groups.length > 0) {
            scope.setGroup(scope.groups[0]);
          }

          // Finished loading
          scope.loading = false;
        });
      }
    };
  }]);
})();
<|endoftext|>


<commit_before>function Muppet(age, hobby) {
  this.age = age;
  this.hobby = hobby;

  this.answerNanny = function(){
	return "Everything's cool!";
  }
}

function SwedishChef(age, hobby, mood) {
  Muppet.call(this, age, hobby);
  this.mood = mood;

  this.cook = function() {
    return "Mmmm soup!";
  }
}

SwedishChef.prototype = new Muppet();

describe("About inheritance", function() {
  beforeEach(function(){
    this.muppet = new Muppet(2, "coding");
  	this.swedishChef = new SwedishChef(2, "cooking", "chillin");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.swedishChef.cook()).toEqual("Mmmm soup!");
  });

  it("should be able to call a method on the base object", function() {
    expect(this.swedishChef.answerNanny()).toEqual("Everything's cool!");
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.swedishChef.age).toEqual(FILL_ME_IN);
    expect(this.swedishChef.hobby).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.swedishChef.mood).toEqual(FILL_ME_IN);
  });
});

// http://javascript.crockford.com/prototypal.html
Object.prototype.beget = function () {
  function F() {}
  F.prototype = this;
  return new F();
}

function Gonzo(age, hobby, trick) {
  Muppet.call(this, age, hobby);
  this.trick = trick;

  this.doTrick = function() {
    return this.trick;
  }
}

//no longer need to call the Muppet (base type) constructor
Gonzo.prototype = Muppet.prototype.beget();
//note: if you're wondering how this line affects the below tests, the answer is that it doesn't.
//however, it does do something interesting -- it makes this work:
//  var g = new Gonzo(...);
//  g instanceOf Muppet //true

describe("About Crockford's inheritance improvement", function() {
  beforeEach(function(){
    this.gonzo = new Gonzo(3, "daredevil performer", "eat a tire");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.gonzo.doTrick()).toEqual(FILL_ME_IN);
  });

  it("should be able to call a method on the base object", function() {
    expect(this.gonzo.answerNanny()).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.gonzo.age).toEqual(FILL_ME_IN);
    expect(this.gonzo.hobby).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.gonzo.trick).toEqual(FILL_ME_IN);
  });
});
<commit_msg>"Fixed: AboutInheritance.js - Problem (3) : it('should set constructor parameters on the base object..'"<commit_after>function Muppet(age, hobby) {
  this.age = age;
  this.hobby = hobby;

  this.answerNanny = function(){
	return "Everything's cool!";
  }
}

function SwedishChef(age, hobby, mood) {
  Muppet.call(this, age, hobby);
  this.mood = mood;

  this.cook = function() {
    return "Mmmm soup!";
  }
}

SwedishChef.prototype = new Muppet();

describe("About inheritance", function() {
  beforeEach(function(){
    this.muppet = new Muppet(2, "coding");
  	this.swedishChef = new SwedishChef(2, "cooking", "chillin");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.swedishChef.cook()).toEqual("Mmmm soup!");
  });

  it("should be able to call a method on the base object", function() {
    expect(this.swedishChef.answerNanny()).toEqual("Everything's cool!");
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.swedishChef.age).toEqual(2);
    expect(this.swedishChef.hobby).toEqual("cooking");
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.swedishChef.mood).toEqual(FILL_ME_IN);
  });
});

// http://javascript.crockford.com/prototypal.html
Object.prototype.beget = function () {
  function F() {}
  F.prototype = this;
  return new F();
}

function Gonzo(age, hobby, trick) {
  Muppet.call(this, age, hobby);
  this.trick = trick;

  this.doTrick = function() {
    return this.trick;
  }
}

//no longer need to call the Muppet (base type) constructor
Gonzo.prototype = Muppet.prototype.beget();
//note: if you're wondering how this line affects the below tests, the answer is that it doesn't.
//however, it does do something interesting -- it makes this work:
//  var g = new Gonzo(...);
//  g instanceOf Muppet //true

describe("About Crockford's inheritance improvement", function() {
  beforeEach(function(){
    this.gonzo = new Gonzo(3, "daredevil performer", "eat a tire");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.gonzo.doTrick()).toEqual(FILL_ME_IN);
  });

  it("should be able to call a method on the base object", function() {
    expect(this.gonzo.answerNanny()).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.gonzo.age).toEqual(FILL_ME_IN);
    expect(this.gonzo.hobby).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.gonzo.trick).toEqual(FILL_ME_IN);
  });
});
<|endoftext|>