<commit_before>function dateSplitter(date) {
  var dateArray = date.split("-");
  return dateArray[1] + "/" + dateArray[2] + "/" + dateArray[0];
}

function emptyDivs() {
  $("#events").empty();
  $("#songs").empty();
  $("#movies").empty();
  $(".facebook").empty();
  $(".twitter").empty();
  $("#conceptionRange").empty();
  $("#about-text").hide();
  $(".data-returned").hide();
  $("#moreOptions").hide();
  $("#emailInput").hide();
  $("#senderInput").hide();
  $("#emailSubmitButton").hide();
}

function checkUrl(url) {
  url = url.replace("http://localhost:3002/", "");
  url = url.replace("http://www.xmarksyourstart.com/", "");
  url = url.replace("https://www.xmarksyourstart.com/", "");
  if (url === ""){
    return true;
  } else {
    return url;
  }
}

function addYoutubeVideo(type, id) {
  var start = '';

  $("#" + type + "s").append(start + id + end);
}

function getOldMovie(year, code) {
  $.ajax({
    method: "GET",
    url: "/old_movie",
    data: "year=" + year + "&code=" + code
  })
  .done(function(data) {
    $("#movies").append("
Sorry, there is no box office data available for the specific date of your conception. The highest grossing film of " + year + " was " + data[0][0].title + "
");
    addYoutubeVideo("movie", data[0][0].link);
  });
}

function getAllOTDTypes(startDate, endDate) {
  var types = ["event", "song", "movie", "weather"];
  for(var i = 0; i < types.length; i++) {
    $.ajax({
      method: "GET",
      url: "/on_this_day_range",
      data: "start=" + startDate + "&end=" + endDate + "&type=" + types[i]
    })
    .done(function(data) {
      for (var j = 0; j < data.length; j++) {
        if (data[0].info !== undefined) {
          $("#events").append("
" + data[j].info + "
");
        } else if (data[0].type !== undefined) {
          $("#events").append("
" + data[0].message + "
");
          break;
        } else if (data[0].artist !== undefined) {
          $("#songs").append("
" + data[j].title + " by " + data[j].artist + "
");
          addYoutubeVideo("song", data[0].link);
        } else {
          $("#movies").append("
" + data[j].title + "
");
          addYoutubeVideo("movie", data[0].link);
        }
      }
    });
  }
  var test = parseInt(endDate.substring(6,10));
  if (test < 1960) {
    getOldMovie(test, test + "0000");
  }
}

function getAllData(birthday, unusual, number, modifier) {
  $.ajax({
    method: "GET",
    url: "/conception_range",
    data: "birthday=" + birthday + "&unusual=" + unusual + "&number=" + number + "&modifier=" + modifier
  })
  .done(function(data) {
    if (data[0].error === false) {
      $(".birthdayError").append("
 This is not a valid birthday.
");
    } else {
      $(".birthdayError").empty();
      var startDate = dateSplitter(data[0]);
      var endDate   = dateSplitter(data[1]);

      $("#conceptionRange").append("You were likely conceived between " + startDate + " and " + endDate + ".");
      getAllOTDTypes(startDate, endDate);
    }
  });
}

function sendEmail(person, sender, message) {
  $.ajax({
    method: "GET",
    url: "/send_email",
    data: "person=" + person + "&sender=" + sender + "&message=" + message
  })
  .done(function(data) {
    $(".error").append('
' + data[0].flash + '
');
  });
}

window.requestAnimationFrame(function () {
  var response = checkUrl(window.location.href);
  if (response === true) {
    emptyDivs();
    $("#checkUnusual").click(function() {
      $("#moreOptions").toggle();
    });
    $(".about").click(function() {
      $("#about-text").toggle();
    });
    $(".emailInputButton").click(function() {
      $("#emailInput").toggle();
      $("#senderInput").toggle();
      $("#emailSubmitButton").toggle();
      $(".emailInputButton").hide();
    });

    $(".toggle-btn:not('.noscript') input[type=radio]").addClass("visuallyhidden");
    $(".toggle-btn:not('.noscript') input[type=radio]").change(function() {
      if( $(this).attr("name") ) {
          $(this).parent().addClass("success").siblings().removeClass("success");
      } else {
          $(this).parent().toggleClass("success");
      }
    });
    $("#birthdayInputButton").click(function() {
      emptyDivs();
      var output = $("#birthdayInput").val();
      var birthday = dateSplitter(output);
      var splitOutput = output.split("-");
      var combOutput = splitOutput[0] + splitOutput[1] + splitOutput[2];
      var unusual = ($("#checkUnusual:checkbox:checked").length > 0);
      var number = $('#actualBirthInput').val();
      var modifier = $('.success').text();
      getAllData(birthday, unusual, number, modifier);
      $(".data-returned").show();
      var fb_a = 'Share on Facebook ';

      var facebook_html = fb_a + combOutput + fb_b + fb_c + fb_d + fb_e;

      var tw_a = 'Share on Twitter ';

      var twitter_html = tw_a + combOutput + tw_b + fb_c + fb_d + tw_e;

      //var twitter_html = 'Share This on Twitter';

      $(".facebook").append(facebook_html);
      $(".twitter").append(twitter_html);

    });
    $("#emailSubmitButton").click(function() {
      var person = $("#emailInput").val();
      var sender = $("#senderInput").val();
      var output = $("#birthdayInput").val();
      var splitOutput = output.split("-");
      var combOutput = splitOutput[0] + splitOutput[1] + splitOutput[2];
      sendEmail(person, sender, combOutput);
    });

  } else {
    var year = response.substring(0,4);
    var month = response.substring(4,6);
    var day = response.substring(6,8);
    var birthday = month + "/" + day + "/" + year;
    var unusual = false;
    var number = 0;
    var modifier = "early";
    getAllData(birthday, unusual, number, modifier);
  }
});
<commit_msg>Multiple songs displayed bug fix<commit_after>function dateSplitter(date) {
  var dateArray = date.split("-");
  return dateArray[1] + "/" + dateArray[2] + "/" + dateArray[0];
}

function emptyDivs() {
  $("#events").empty();
  $("#songs").empty();
  $("#movies").empty();
  $(".facebook").empty();
  $(".twitter").empty();
  $("#conceptionRange").empty();
  $("#about-text").hide();
  $(".data-returned").hide();
  $("#moreOptions").hide();
  $("#emailInput").hide();
  $("#senderInput").hide();
  $("#emailSubmitButton").hide();
}

function checkUrl(url) {
  url = url.replace("http://localhost:3002/", "");
  url = url.replace("http://www.xmarksyourstart.com/", "");
  url = url.replace("https://www.xmarksyourstart.com/", "");
  if (url === ""){
    return true;
  } else {
    return url;
  }
}

function addYoutubeVideo(type, id) {
  var start = '';

  $("#" + type + "s").append(start + id + end);
}

function getOldMovie(year, code) {
  $.ajax({
    method: "GET",
    url: "/old_movie",
    data: "year=" + year + "&code=" + code
  })
  .done(function(data) {
    $("#movies").append("
Sorry, there is no box office data available for the specific date of your conception. The highest grossing film of " + year + " was " + data[0][0].title + "
");
    addYoutubeVideo("movie", data[0][0].link);
  });
}

function getAllOTDTypes(startDate, endDate) {
  var types = ["event", "song", "movie", "weather"];
  for(var i = 0; i < types.length; i++) {
    $.ajax({
      method: "GET",
      url: "/on_this_day_range",
      data: "start=" + startDate + "&end=" + endDate + "&type=" + types[i]
    })
    .done(function(data) {
      for (var j = 0; j < data.length; j++) {
        if (data[0].info !== undefined) {
          $("#events").append("
" + data[j].info + "
");
        } else if (data[0].type !== undefined) {
          $("#events").append("
" + data[0].message + "
");
          break;
        } else if (data[0].artist !== undefined) {
          $("#songs").append("
" + data[0].title + " by " + data[j].artist + "
");
          addYoutubeVideo("song", data[0].link);
          break;
        } else {
          $("#movies").append("
" + data[0].title + "
");
          addYoutubeVideo("movie", data[0].link);
          break;
        }
      }
    });
  }
  var test = parseInt(endDate.substring(6,10));
  if (test < 1960) {
    getOldMovie(test, test + "0000");
  }
}

function getAllData(birthday, unusual, number, modifier) {
  $.ajax({
    method: "GET",
    url: "/conception_range",
    data: "birthday=" + birthday + "&unusual=" + unusual + "&number=" + number + "&modifier=" + modifier
  })
  .done(function(data) {
    if (data[0].error === false) {
      $(".birthdayError").append("
 This is not a valid birthday.
");
    } else {
      $(".birthdayError").empty();
      var startDate = dateSplitter(data[0]);
      var endDate   = dateSplitter(data[1]);

      $("#conceptionRange").append("You were likely conceived between " + startDate + " and " + endDate + ".");
      getAllOTDTypes(startDate, endDate);
    }
  });
}

function sendEmail(person, sender, message) {
  $.ajax({
    method: "GET",
    url: "/send_email",
    data: "person=" + person + "&sender=" + sender + "&message=" + message
  })
  .done(function(data) {
    $(".error").append('
' + data[0].flash + '
');
  });
}

window.requestAnimationFrame(function () {
  var response = checkUrl(window.location.href);
  if (response === true) {
    emptyDivs();
    $("#checkUnusual").click(function() {
      $("#moreOptions").toggle();
    });
    $(".about").click(function() {
      $("#about-text").toggle();
    });
    $(".emailInputButton").click(function() {
      $("#emailInput").toggle();
      $("#senderInput").toggle();
      $("#emailSubmitButton").toggle();
      $(".emailInputButton").hide();
    });

    $(".toggle-btn:not('.noscript') input[type=radio]").addClass("visuallyhidden");
    $(".toggle-btn:not('.noscript') input[type=radio]").change(function() {
      if( $(this).attr("name") ) {
          $(this).parent().addClass("success").siblings().removeClass("success");
      } else {
          $(this).parent().toggleClass("success");
      }
    });
    $("#birthdayInputButton").click(function() {
      emptyDivs();
      var output = $("#birthdayInput").val();
      var birthday = dateSplitter(output);
      var splitOutput = output.split("-");
      var combOutput = splitOutput[0] + splitOutput[1] + splitOutput[2];
      var unusual = ($("#checkUnusual:checkbox:checked").length > 0);
      var number = $('#actualBirthInput').val();
      var modifier = $('.success').text();
      getAllData(birthday, unusual, number, modifier);
      $(".data-returned").show();
      var fb_a = 'Share on Facebook ';

      var facebook_html = fb_a + combOutput + fb_b + fb_c + fb_d + fb_e;

      var tw_a = 'Share on Twitter ';

      var twitter_html = tw_a + combOutput + tw_b + fb_c + fb_d + tw_e;

      //var twitter_html = 'Share This on Twitter';

      $(".facebook").append(facebook_html);
      $(".twitter").append(twitter_html);

    });
    $("#emailSubmitButton").click(function() {
      var person = $("#emailInput").val();
      var sender = $("#senderInput").val();
      var output = $("#birthdayInput").val();
      var splitOutput = output.split("-");
      var combOutput = splitOutput[0] + splitOutput[1] + splitOutput[2];
      sendEmail(person, sender, combOutput);
    });

  } else {
    var year = response.substring(0,4);
    var month = response.substring(4,6);
    var day = response.substring(6,8);
    var birthday = month + "/" + day + "/" + year;
    var unusual = false;
    var number = 0;
    var modifier = "early";
    getAllData(birthday, unusual, number, modifier);
  }
});
<|endoftext|>


<commit_before>function setup(data, strategies, strategy_ids) {

  var options = {
    series: {
        lines: { show: true },
        points: { show: true },
    },
    xaxis: { mode: 'time',
             timezone: 'browser',
             timeformat: "%m/%d %I%p",
             tickSize: [1, "hour"]},
    legend: { position: 'nw',
              container: '#legend'},
    grid: {clickable: true}
  };

  var dset = []
  dset.push({label: "strategy",
             data: strategies,
             yaxis: 2,
             color: 'grey',
             bars: {show: false},
             lines: {show: false},
             points: {radius: 8}})

  var color_index = 0;
  for(var market_id in data) {
    dset.push({label: data[market_id][0]+" ask",
               data: data[market_id][2],
               color: color_index,
               points: {radius: 5}})
    dset.push({label: data[market_id][0]+" bid",
               data: data[market_id][1],
               color: color_index,
               })
    color_index = color_index + 1;
  }

  $.plot($("#chart"), dset, options);
  $("#chart").bind('plotclick', function(e,p,i){strategyClick(e,p,i,strategy_ids)})
}

function chart_setup(data) {

  var options = {
    series: {
        lines: { show: true },
        points: { show: true },
    },
  };

  var dset = []
  for(var id in data) {
    dset.push({label: data[id][0],
               data: data[id][1],
               })
  }

  console.log(dset)
  $.plot($("#chart"), dset, options);
}

function strategyClick(event, point, item, strategy_ids) {
      console.log(item.dataIndex);
      console.log(item.seriesIndex);
      if(item.seriesIndex == 0) {
        window.location = "?strategy_id="+strategy_ids[item.dataIndex]
      }
}<commit_msg>dollar signs on the second y axis<commit_after>function setup(data, strategies, strategy_ids) {

  var options = {
    series: {
        lines: { show: true },
        points: { show: true },
    },
    xaxis: { mode: 'time',
             timezone: 'browser',
             timeformat: "%m/%d %I%p",
             tickSize: [1, "hour"]},
    legend: { position: 'nw',
              container: '#legend'},
    yaxis: { tickFormatter: formatter},
    grid: {clickable: true}
  };

  var dset = []
  dset.push({label: "strategy",
             data: strategies,
             yaxis: 2,
             color: 'grey',
             bars: {show: false},
             lines: {show: false},
             points: {radius: 8}})

  var color_index = 0;
  for(var market_id in data) {
    dset.push({label: data[market_id][0]+" ask",
               data: data[market_id][2],
               color: color_index,
               points: {radius: 5}})
    dset.push({label: data[market_id][0]+" bid",
               data: data[market_id][1],
               color: color_index,
               })
    color_index = color_index + 1;
  }

  $.plot($("#chart"), dset, options);
  $("#chart").bind('plotclick', function(e,p,i){strategyClick(e,p,i,strategy_ids)})
}

function chart_setup(data) {

  var options = {
    series: {
        lines: { show: true },
        points: { show: true },
    },
  };

  var dset = []
  for(var id in data) {
    dset.push({label: data[id][0],
               data: data[id][1],
               })
  }

  console.log(dset)
  $.plot($("#chart"), dset, options);
}

function strategyClick(event, point, item, strategy_ids) {
      console.log(item.dataIndex);
      console.log(item.seriesIndex);
      if(item.seriesIndex == 0) {
        window.location = "?strategy_id="+strategy_ids[item.dataIndex]
      }
}

function formatter(val, axis) {
  if(axis.n == 1)
    return val.toFixed(axis.tickDecimals);
  if(axis.n == 2)
    return "$"+val.toFixed(axis.tickDecimals);
}
<|endoftext|>


<commit_before>var Hpi = function() {
  "use strict";

  /** Module initialisation */
  var init = function() {
    initControls();
    bindEvents();
    drawPreview();
  };

  /** Event handling */
  var bindEvents = function() {
    $(".container").on( "click", "a.action-add-comparison", onAddComparison );
    $(".container").on( "click", "a.action-show-map", onShowMap );
    $(".container").on( "click", "a.action-remove-comparison", onRemoveComparison );
    $(".container").on( "click", "a.action-remove-selection", onRemoveSelection );

    $("form.search").on( "submit", onSearchSubmit );

    $("form.preview").on( "click", "input", onChangePreviewSettings );
    $("form.preview").on( "change", ".dates-filter select", drawPreview );
    $("form.preview").on( "click", "a.action-set-dates", onChangeDates );
  };

  /** Widget and control initialisation */
  var initControls = function() {
    $("button#action_search").hide();
    $("form.preview input[type=submit]").hide();

    // ensure we know which input field the user is entering text into
    $("form.search input:not([type=hidden])").each( function( i, elem ) {
      var sId = searchIdFromElement( elem );

      $(elem).autocomplete({
        source: HpiLocations.locationNames,
        autoFocus: true,
        select: function( e, ui ) {
          onAutocompleteSelect( sId, e, ui );
        },
        focus: function (event, ui) {
           event.preventDefault();
        }
      });
    } );

    // add show map buttons
    $(".js.map-button").each( function( i, elem ) {
      showMapButton( elem );
    } );
  };

  /** User has submitted a search on the search form */
  var onSearchSubmit = function( e ) {
    if (e) {e.preventDefault();}
  };

  /** User has selected one of the autocomplete options */
  var onAutocompleteSelect = function( searchId, e, ui ) {
    e.preventDefault();

    var locationName = ui.item.label;
    var locationURI = ui.item.value;

    $("input#" + searchId.sym).val( "" );
    selectLocation( locationName, locationURI, searchId, e.target );
  };

  /** User has clicked to change some of the preview settings */
  var onChangePreviewSettings = function( e ) {
    drawPreview();
  };

  /** Show that a location has been selected by the user */
  var selectLocation = function( locationName, locationURI, sId, targetElem ) {
    var searchId = asSearchId( sId );
    showSelectedLocation( targetElem, searchId, locationName, locationURI );
    drawPreview();
  };

  var drawPreview = function() {
    // TODO this really refactoring to DRY it up
    if (locationComplete()) {
      resetPreviewFormElement( "loc_0", selectedLocationName( 0 ) );
      resetPreviewFormElement( "loc_uri_0", selectedLocationURI( 0 ) );

      resetPreviewFormElement( "loc_1", compareAreas() ? selectedLocationName( 1 ) : null );
      resetPreviewFormElement( "loc_uri_1", compareAreas() ? selectedLocationURI( 1 ) : null );

      if (compareAreas()) {
        resetPreviewFormElement( "compare", 1 );
      }

      HpiPreview.updatePreview();
    }
  };

  var resetPreviewFormElement = function( elemName, val ) {
    var elem = $(sprintf("form.preview input[type=hidden][name=%s]", elemName ) );
    if (elem.length) {
      // input element exists
      if (val) {
        elem.val( val );
      }
      else {
        elem.remove();
      }
    }
    else {
      // element does not yet exist
      if (val) {
        $("form.preview").append(sprintf( "<input type='hidden' name='%s' value='%s' />", elemName, val ) );
      }
    }
  };

  var forgetSelectedLocation = function( sid ) {
    console.log( "Forgetting selected location " + sid );
    locationFormElement( sid, "loc" ).remove();
    locationFormElement( sid, "loc_uri" ).remove();
  };

  var selectedLocationName = function( sid ) {
    return locationFormElement( sid, "loc" ).val();
  };

  var selectedLocationURI = function( sid ) {
    return locationFormElement( sid, "loc_uri" ).val();
  };

  var locationFormElement = function( sid, l ) {
    var li = attributeWithSearchId( l, asSearchId( sid ) );
    return $( sprintf( "form.search input[type=hidden][name=%s]", li ) );
  };

  /** Return true if we have all necessary locations that we can begin query */
  var locationComplete = function() {
    var location0 = selectedLocationURI( 0 );
    var location1 = selectedLocationURI( 1 );

    return compareAreas() ? (location0 && location1) : location0;
  };

  /** Return true if we are performing a comparison */
  var compareAreas = function() {
    return $("form.search input[type=hidden][name=compare]").length;
  };

  /* Return loc or loc_compare as the identity of the search the user is conducting */
  var searchIdFromElement = function( elem ) {
    var sId = $(elem).attr( "name" );
    return asSearchId( parseInt( sId.replace( /[^\d]*/, "" ) ) );
  };

  /** Return a search ID object for search N */
  var asSearchId = function( i ) {
    return _.isNumber( i ) ? {n: i, sym: "search_" + i } : i;
  };

  /** Return a symbol tagged with the search ID */
  var attributeWithSearchId = function( sym, searchId ) {
    return sprintf( "%s_%d", sym, searchId.n );
  };

  /** User has selected a location */
  var showSelectedLocation = function( sourceElem, searchId, locationName, locationURI ) {
    var elem = $(sourceElem).parents(".area-selection")
                            .find(".selected-search-term")
                            .empty()
                            .append( sprintf( "
Selected: %s " +
                                              "" +
                                              "
",
                                              locationName ) )
                            .append( sprintf( "<input type='hidden' name='%s' value='%s' />",
                                     attributeWithSearchId( "loc", searchId ), locationName ) )
                            .append( sprintf( "<input type='hidden' name='%s' value='%s' />",
                                     attributeWithSearchId( "loc_uri", searchId ), locationURI ) );

    if (compareAreas()) {
      elem.append( "<input type='hidden' name='compare' value='1' />" );
    }
  };

  /** User wants to show the comparison region */
  var onAddComparison = function( e ) {
    e.preventDefault();
    clearPreview();

    var interactionState = currentInteractionState( "search",
                                                    {compare: 1},
                                                    ['search_0', 'search_1'] );
    $.post( Routes.search_index_path(),
            interactionState, null, "html" )
      .done( onComparisonDone )
      .fail( onComparisonFail );
  };

  var onComparisonDone = function( html ) {
    $(".search-form-container").empty().append( html );
    initControls();
    drawPreview();
  };

  var onComparisonFail = function( jqXhr, error ) {
    console.log( "Comparison failure: " + error );
  };

  /** User wants to remove the comparison of two areas option */
  var onRemoveComparison = function( e ) {
    e.preventDefault();
    clearPreview();
    resetPreviewFormElement( "compare", null );

    var interactionState = currentInteractionState( "search",
                                                    {},
                                                    ['compare', 'search_1', 'loc_1', 'loc_uri_1'] );
    $.post( Routes.search_index_path(),
            interactionState, null, "html" )
      .done( onComparisonDone )
      .fail( onComparisonFail );
  };

  /** Return the current interaction state as a hash */
  var currentInteractionState = function( formClass, options, deletes ) {
    var state = $(sprintf( "form.%s", formClass) ).serializeHash();
    state = _.extend( state, options || {} );

    _.each( (deletes || []), function( d ) {
      delete state[d];
    } );

    return state;
  };

  /** Remove a selection */
  var onRemoveSelection = function( e ) {
    e.preventDefault();
    var button = $(e.currentTarget);
    var elem = button.parents(".area-selection").find(".selected-search-term");
    var input = elem.find( "input" );
    var searchId = input.attr("name");

    elem.empty();
    clearPreview();
  }

  var clearPreview = function() {
    $("#results-preview").empty();
    $("#results-header").empty();
  };

  /** Ensure a show-map button is present for the element */
  var showMapButton = function( elem ) {
    if ($(elem).find( "button" ).length === 0) {
      var alt = 'find a location on the map';
      $(elem).append( sprintf( "" +
                               "",
                               alt, alt ) );
    }
  };

  /** User has clicked to show the map */
  var onShowMap = function( e ) {
    e.preventDefault();
    var button = $(e.currentTarget);
    var searchId = button.parents( "span[data-search-id]" ).data( "search-id" );

    HpiMapSearch.showDialogue( searchId, e.currentTarget );
  };

  /** User has selected an option to pick an alternative date range */
  var onChangeDates = function( e ) {
    e.preventDefault();
    var a = $(e.currentTarget);
    $("select#from_m").val( a.data( "from-m" ));
    $("select#from_y").val( a.data( "from-y" ));
    $("select#to_m").val( a.data( "to-m" ));
    $("select#to_y").val( a.data( "to-y" )).change();

  };

  return {
    init: init,
    currentInteractionState: currentInteractionState,
    selectLocation: selectLocation
  }
}();

$( Hpi.init );
<commit_msg>Set minimum autocomplete input length<commit_after>var Hpi = function() {
  "use strict";

  /** Module initialisation */
  var init = function() {
    initControls();
    bindEvents();
    drawPreview();
  };

  /** Event handling */
  var bindEvents = function() {
    $(".container").on( "click", "a.action-add-comparison", onAddComparison );
    $(".container").on( "click", "a.action-show-map", onShowMap );
    $(".container").on( "click", "a.action-remove-comparison", onRemoveComparison );
    $(".container").on( "click", "a.action-remove-selection", onRemoveSelection );

    $("form.search").on( "submit", onSearchSubmit );

    $("form.preview").on( "click", "input", onChangePreviewSettings );
    $("form.preview").on( "change", ".dates-filter select", drawPreview );
    $("form.preview").on( "click", "a.action-set-dates", onChangeDates );
  };

  /** Widget and control initialisation */
  var initControls = function() {
    $("button#action_search").hide();
    $("form.preview input[type=submit]").hide();

    // ensure we know which input field the user is entering text into
    $("form.search input:not([type=hidden])").each( function( i, elem ) {
      var sId = searchIdFromElement( elem );

      $(elem).autocomplete({
        source: HpiLocations.locationNames,
        autoFocus: true,
        minLength: 3,
        select: function( e, ui ) {
          onAutocompleteSelect( sId, e, ui );
        },
        focus: function (event, ui) {
           event.preventDefault();
        }
      });
    } );

    // add show map buttons
    $(".js.map-button").each( function( i, elem ) {
      showMapButton( elem );
    } );
  };

  /** User has submitted a search on the search form */
  var onSearchSubmit = function( e ) {
    if (e) {e.preventDefault();}
  };

  /** User has selected one of the autocomplete options */
  var onAutocompleteSelect = function( searchId, e, ui ) {
    e.preventDefault();

    var locationName = ui.item.label;
    var locationURI = ui.item.value;

    $("input#" + searchId.sym).val( "" );
    selectLocation( locationName, locationURI, searchId, e.target );
  };

  /** User has clicked to change some of the preview settings */
  var onChangePreviewSettings = function( e ) {
    drawPreview();
  };

  /** Show that a location has been selected by the user */
  var selectLocation = function( locationName, locationURI, sId, targetElem ) {
    var searchId = asSearchId( sId );
    showSelectedLocation( targetElem, searchId, locationName, locationURI );
    drawPreview();
  };

  var drawPreview = function() {
    // TODO this really refactoring to DRY it up
    if (locationComplete()) {
      resetPreviewFormElement( "loc_0", selectedLocationName( 0 ) );
      resetPreviewFormElement( "loc_uri_0", selectedLocationURI( 0 ) );

      resetPreviewFormElement( "loc_1", compareAreas() ? selectedLocationName( 1 ) : null );
      resetPreviewFormElement( "loc_uri_1", compareAreas() ? selectedLocationURI( 1 ) : null );

      if (compareAreas()) {
        resetPreviewFormElement( "compare", 1 );
      }

      HpiPreview.updatePreview();
    }
  };

  var resetPreviewFormElement = function( elemName, val ) {
    var elem = $(sprintf("form.preview input[type=hidden][name=%s]", elemName ) );
    if (elem.length) {
      // input element exists
      if (val) {
        elem.val( val );
      }
      else {
        elem.remove();
      }
    }
    else {
      // element does not yet exist
      if (val) {
        $("form.preview").append(sprintf( "<input type='hidden' name='%s' value='%s' />", elemName, val ) );
      }
    }
  };

  var forgetSelectedLocation = function( sid ) {
    console.log( "Forgetting selected location " + sid );
    locationFormElement( sid, "loc" ).remove();
    locationFormElement( sid, "loc_uri" ).remove();
  };

  var selectedLocationName = function( sid ) {
    return locationFormElement( sid, "loc" ).val();
  };

  var selectedLocationURI = function( sid ) {
    return locationFormElement( sid, "loc_uri" ).val();
  };

  var locationFormElement = function( sid, l ) {
    var li = attributeWithSearchId( l, asSearchId( sid ) );
    return $( sprintf( "form.search input[type=hidden][name=%s]", li ) );
  };

  /** Return true if we have all necessary locations that we can begin query */
  var locationComplete = function() {
    var location0 = selectedLocationURI( 0 );
    var location1 = selectedLocationURI( 1 );

    return compareAreas() ? (location0 && location1) : location0;
  };

  /** Return true if we are performing a comparison */
  var compareAreas = function() {
    return $("form.search input[type=hidden][name=compare]").length;
  };

  /* Return loc or loc_compare as the identity of the search the user is conducting */
  var searchIdFromElement = function( elem ) {
    var sId = $(elem).attr( "name" );
    return asSearchId( parseInt( sId.replace( /[^\d]*/, "" ) ) );
  };

  /** Return a search ID object for search N */
  var asSearchId = function( i ) {
    return _.isNumber( i ) ? {n: i, sym: "search_" + i } : i;
  };

  /** Return a symbol tagged with the search ID */
  var attributeWithSearchId = function( sym, searchId ) {
    return sprintf( "%s_%d", sym, searchId.n );
  };

  /** User has selected a location */
  var showSelectedLocation = function( sourceElem, searchId, locationName, locationURI ) {
    var elem = $(sourceElem).parents(".area-selection")
                            .find(".selected-search-term")
                            .empty()
                            .append( sprintf( "
Selected: %s " +
                                              "" +
                                              "
",
                                              locationName ) )
                            .append( sprintf( "<input type='hidden' name='%s' value='%s' />",
                                     attributeWithSearchId( "loc", searchId ), locationName ) )
                            .append( sprintf( "<input type='hidden' name='%s' value='%s' />",
                                     attributeWithSearchId( "loc_uri", searchId ), locationURI ) );

    if (compareAreas()) {
      elem.append( "<input type='hidden' name='compare' value='1' />" );
    }
  };

  /** User wants to show the comparison region */
  var onAddComparison = function( e ) {
    e.preventDefault();
    clearPreview();

    var interactionState = currentInteractionState( "search",
                                                    {compare: 1},
                                                    ['search_0', 'search_1'] );
    $.post( Routes.search_index_path(),
            interactionState, null, "html" )
      .done( onComparisonDone )
      .fail( onComparisonFail );
  };

  var onComparisonDone = function( html ) {
    $(".search-form-container").empty().append( html );
    initControls();
    drawPreview();
  };

  var onComparisonFail = function( jqXhr, error ) {
    console.log( "Comparison failure: " + error );
  };

  /** User wants to remove the comparison of two areas option */
  var onRemoveComparison = function( e ) {
    e.preventDefault();
    clearPreview();
    resetPreviewFormElement( "compare", null );

    var interactionState = currentInteractionState( "search",
                                                    {},
                                                    ['compare', 'search_1', 'loc_1', 'loc_uri_1'] );
    $.post( Routes.search_index_path(),
            interactionState, null, "html" )
      .done( onComparisonDone )
      .fail( onComparisonFail );
  };

  /** Return the current interaction state as a hash */
  var currentInteractionState = function( formClass, options, deletes ) {
    var state = $(sprintf( "form.%s", formClass) ).serializeHash();
    state = _.extend( state, options || {} );

    _.each( (deletes || []), function( d ) {
      delete state[d];
    } );

    return state;
  };

  /** Remove a selection */
  var onRemoveSelection = function( e ) {
    e.preventDefault();
    var button = $(e.currentTarget);
    var elem = button.parents(".area-selection").find(".selected-search-term");
    var input = elem.find( "input" );
    var searchId = input.attr("name");

    elem.empty();
    clearPreview();
  }

  var clearPreview = function() {
    $("#results-preview").empty();
    $("#results-header").empty();
  };

  /** Ensure a show-map button is present for the element */
  var showMapButton = function( elem ) {
    if ($(elem).find( "button" ).length === 0) {
      var alt = 'find a location on the map';
      $(elem).append( sprintf( "" +
                               "",
                               alt, alt ) );
    }
  };

  /** User has clicked to show the map */
  var onShowMap = function( e ) {
    e.preventDefault();
    var button = $(e.currentTarget);
    var searchId = button.parents( "span[data-search-id]" ).data( "search-id" );

    HpiMapSearch.showDialogue( searchId, e.currentTarget );
  };

  /** User has selected an option to pick an alternative date range */
  var onChangeDates = function( e ) {
    e.preventDefault();
    var a = $(e.currentTarget);
    $("select#from_m").val( a.data( "from-m" ));
    $("select#from_y").val( a.data( "from-y" ));
    $("select#to_m").val( a.data( "to-m" ));
    $("select#to_y").val( a.data( "to-y" )).change();

  };

  return {
    init: init,
    currentInteractionState: currentInteractionState,
    selectLocation: selectLocation
  }
}();

$( Hpi.init );
<|endoftext|>


<commit_before>/**
 * Graphology Utils Specs
 * =======================
 *
 * Testing the utils methods.
 */
import assert from 'assert';
import {addNodesFrom} from './helpers';

const PROPERTIES = ['type', 'multi', 'map', 'selfLoops'];

export default function utils(Graph) {
  return {
    '#.nullCopy': {
      'it should create an null copy of the graph.': function () {
        const graph = new Graph();
        addNodesFrom(graph, ['John', 'Thomas']);
        graph.addEdge('John', 'Thomas');

        const copy = graph.nullCopy();

        assert.deepStrictEqual(copy.nodes(), []);
        assert.strictEqual(copy.order, 0);
        assert.strictEqual(copy.size, 0);

        PROPERTIES.forEach(property => {
          assert.strictEqual(graph[property], copy[property]);
        });
      },

      'it should be possible to pass options to merge.': function () {
        const graph = new Graph({type: 'directed'});

        const copy = graph.nullCopy({type: 'undirected'});

        assert.strictEqual(copy.type, 'undirected');

        assert.throws(function () {
          copy.addDirectedEdge('one', 'two');
        }, /addDirectedEdge/);
      }
    },

    '#.emptyCopy': {
      'it should create an empty copy of the graph.': function () {
        const graph = new Graph();
        addNodesFrom(graph, ['John', 'Thomas']);
        graph.addEdge('John', 'Thomas');

        const copy = graph.emptyCopy();

        assert.deepStrictEqual(copy.nodes(), ['John', 'Thomas']);
        assert.strictEqual(copy.order, 2);
        assert.strictEqual(copy.size, 0);

        PROPERTIES.forEach(property => {
          assert.strictEqual(graph[property], copy[property]);
        });

        copy.mergeEdge('Mary', 'Thomas');
        copy.setNodeAttribute('John', 'age', 32);

        assert.strictEqual(copy.order, 3);
        assert.strictEqual(copy.size, 1);
        assert.deepStrictEqual(copy.getNodeAttributes('John'), {age: 32});
        assert.deepStrictEqual(graph.getNodeAttributes('John'), {});
      },

      'it should be possible to pass options to merge.': function () {
        const graph = new Graph({type: 'directed'});

        const copy = graph.emptyCopy({type: 'undirected'});

        assert.strictEqual(copy.type, 'undirected');

        assert.throws(function () {
          copy.addDirectedEdge('one', 'two');
        }, /addDirectedEdge/);
      }
    },

    '#.copy': {
      'it should create a full copy of the graph.': function () {
        const graph = new Graph();
        addNodesFrom(graph, ['John', 'Thomas']);
        graph.addEdge('John', 'Thomas');

        const copy = graph.copy();

        assert.deepStrictEqual(copy.nodes(), graph.nodes());
        assert.deepStrictEqual(copy.edges(), graph.edges());
        assert.strictEqual(copy.order, 2);
        assert.strictEqual(copy.size, 1);

        PROPERTIES.forEach(property => {
          assert.strictEqual(graph[property], graph[property]);
        });
      },

      'it should not break when copying a graph with wrangled edge ids (issue #213).':
        function () {
          const graph = new Graph();
          graph.addNode('n0');
          graph.addNode('n1');
          graph.addNode('n2');
          graph.addNode('n3');
          graph.addEdge('n0', 'n1');
          graph.addEdge('n1', 'n2');
          graph.addEdge('n2', 'n3');
          graph.addEdge('n3', 'n0');

          assert.doesNotThrow(function () {
            graph.copy();
          });

          // Do surgery on second edge
          const edgeToSplit = graph.edge('n1', 'n2');
          const newNode = 'n12';
          graph.addNode(newNode);
          graph.dropEdge('n1', 'n2');
          graph.addEdge('n1', newNode);
          graph.addEdgeWithKey(edgeToSplit, newNode, 'n2');

          const copy = graph.copy();

          assert.deepStrictEqual(new Set(graph.nodes()), new Set(copy.nodes()));
          assert.deepStrictEqual(new Set(graph.edges()), new Set(copy.edges()));

          assert.notStrictEqual(
            graph.getNodeAttributes('n1'),
            copy.getNodeAttributes('n1')
          );

          assert.doesNotThrow(function () {
            copy.addEdge('n0', 'n12');
          });
        }
    },

    '#.upgradeToMixed': {
      'it should correctly upgrade the given graph to a mixed one.':
        function () {
          const graph = new Graph({type: 'directed'});
          addNodesFrom(graph, [1, 2, 3]);
          graph.addEdgeWithKey('1->2', 1, 2);

          graph.upgradeToMixed();

          assert.strictEqual(graph.type, 'mixed');

          graph.addUndirectedEdge(2, 3);

          assert.strictEqual(graph.size, 2);
          assert.strictEqual(graph.degree(2), 2);
        }
    },

    '#.upgradeToMulti': {
      'it should correctly upgrade the given graph to a multi one.':
        function () {
          const graph = new Graph();
          addNodesFrom(graph, [1, 2]);
          graph.addEdgeWithKey('dA', 1, 2);
          graph.addUndirectedEdgeWithKey('uA', 1, 2);

          graph.upgradeToMulti();

          assert.strictEqual(graph.multi, true);

          graph.addEdgeWithKey('dB', 1, 2);
          graph.addUndirectedEdgeWithKey('uB', 1, 2);

          assert.strictEqual(graph.size, 4);

          assert.deepStrictEqual(graph.edges(), ['dA', 'uA', 'dB', 'uB']);
        }
    }
  };
}
<commit_msg>Adding aversarial unit test for edge key generator Related to #221<commit_after>/**
 * Graphology Utils Specs
 * =======================
 *
 * Testing the utils methods.
 */
import assert from 'assert';
import {addNodesFrom} from './helpers';

const PROPERTIES = ['type', 'multi', 'map', 'selfLoops'];

export default function utils(Graph) {
  return {
    '#.nullCopy': {
      'it should create an null copy of the graph.': function () {
        const graph = new Graph();
        addNodesFrom(graph, ['John', 'Thomas']);
        graph.addEdge('John', 'Thomas');

        const copy = graph.nullCopy();

        assert.deepStrictEqual(copy.nodes(), []);
        assert.strictEqual(copy.order, 0);
        assert.strictEqual(copy.size, 0);

        PROPERTIES.forEach(property => {
          assert.strictEqual(graph[property], copy[property]);
        });
      },

      'it should be possible to pass options to merge.': function () {
        const graph = new Graph({type: 'directed'});

        const copy = graph.nullCopy({type: 'undirected'});

        assert.strictEqual(copy.type, 'undirected');

        assert.throws(function () {
          copy.addDirectedEdge('one', 'two');
        }, /addDirectedEdge/);
      }
    },

    '#.emptyCopy': {
      'it should create an empty copy of the graph.': function () {
        const graph = new Graph();
        addNodesFrom(graph, ['John', 'Thomas']);
        graph.addEdge('John', 'Thomas');

        const copy = graph.emptyCopy();

        assert.deepStrictEqual(copy.nodes(), ['John', 'Thomas']);
        assert.strictEqual(copy.order, 2);
        assert.strictEqual(copy.size, 0);

        PROPERTIES.forEach(property => {
          assert.strictEqual(graph[property], copy[property]);
        });

        copy.mergeEdge('Mary', 'Thomas');
        copy.setNodeAttribute('John', 'age', 32);

        assert.strictEqual(copy.order, 3);
        assert.strictEqual(copy.size, 1);
        assert.deepStrictEqual(copy.getNodeAttributes('John'), {age: 32});
        assert.deepStrictEqual(graph.getNodeAttributes('John'), {});
      },

      'it should be possible to pass options to merge.': function () {
        const graph = new Graph({type: 'directed'});

        const copy = graph.emptyCopy({type: 'undirected'});

        assert.strictEqual(copy.type, 'undirected');

        assert.throws(function () {
          copy.addDirectedEdge('one', 'two');
        }, /addDirectedEdge/);
      }
    },

    '#.copy': {
      'it should create a full copy of the graph.': function () {
        const graph = new Graph();
        addNodesFrom(graph, ['John', 'Thomas']);
        graph.addEdge('John', 'Thomas');

        const copy = graph.copy();

        assert.deepStrictEqual(copy.nodes(), graph.nodes());
        assert.deepStrictEqual(copy.edges(), graph.edges());
        assert.strictEqual(copy.order, 2);
        assert.strictEqual(copy.size, 1);

        PROPERTIES.forEach(property => {
          assert.strictEqual(graph[property], graph[property]);
        });
      },

      'it should not break when copying a graph with wrangled edge ids (issue #213).':
        function () {
          const graph = new Graph();
          graph.addNode('n0');
          graph.addNode('n1');
          graph.addNode('n2');
          graph.addNode('n3');
          graph.addEdge('n0', 'n1');
          graph.addEdge('n1', 'n2');
          graph.addEdge('n2', 'n3');
          graph.addEdge('n3', 'n0');

          assert.doesNotThrow(function () {
            graph.copy();
          });

          // Do surgery on second edge
          const edgeToSplit = graph.edge('n1', 'n2');
          const newNode = 'n12';
          graph.addNode(newNode);
          graph.dropEdge('n1', 'n2');
          graph.addEdge('n1', newNode);
          graph.addEdgeWithKey(edgeToSplit, newNode, 'n2');

          const copy = graph.copy();

          assert.deepStrictEqual(new Set(graph.nodes()), new Set(copy.nodes()));
          assert.deepStrictEqual(new Set(graph.edges()), new Set(copy.edges()));

          assert.notStrictEqual(
            graph.getNodeAttributes('n1'),
            copy.getNodeAttributes('n1')
          );

          assert.doesNotThrow(function () {
            copy.addEdge('n0', 'n12');
          });
        },

      'it should not break on adversarial inputs.': function () {
        let i = 0;

        const edgeKeyGenerator = () => {
          return i++;
        };

        const graph = new Graph({edgeKeyGenerator});

        graph.mergeEdge(0, 1);
        graph.mergeEdge(1, 2);
        graph.mergeEdge(2, 0);

        const copy = graph.copy();

        copy.mergeEdge(3, 4);

        assert.strictEqual(copy.edge(3, 4), '3');

        const serializedCopy = Graph.from(graph.export());

        assert.doesNotThrow(function () {
          serializedCopy.mergeEdge(3, 4);
        });

        assert.strictEqual(serializedCopy.size, 4);
      }
    },

    '#.upgradeToMixed': {
      'it should correctly upgrade the given graph to a mixed one.':
        function () {
          const graph = new Graph({type: 'directed'});
          addNodesFrom(graph, [1, 2, 3]);
          graph.addEdgeWithKey('1->2', 1, 2);

          graph.upgradeToMixed();

          assert.strictEqual(graph.type, 'mixed');

          graph.addUndirectedEdge(2, 3);

          assert.strictEqual(graph.size, 2);
          assert.strictEqual(graph.degree(2), 2);
        }
    },

    '#.upgradeToMulti': {
      'it should correctly upgrade the given graph to a multi one.':
        function () {
          const graph = new Graph();
          addNodesFrom(graph, [1, 2]);
          graph.addEdgeWithKey('dA', 1, 2);
          graph.addUndirectedEdgeWithKey('uA', 1, 2);

          graph.upgradeToMulti();

          assert.strictEqual(graph.multi, true);

          graph.addEdgeWithKey('dB', 1, 2);
          graph.addUndirectedEdgeWithKey('uB', 1, 2);

          assert.strictEqual(graph.size, 4);

          assert.deepStrictEqual(graph.edges(), ['dA', 'uA', 'dB', 'uB']);
        }
    }
  };
}
<|endoftext|>


<commit_before>angular.module('chattyWeather.weather', [])

.controller('WeatherController', function($scope, goGet, $http, $location, Activities, Food) {
	var weatherData;
  $scope.phrase = ". . loading . .";
  $scope.food;
  $scope.prop;
  $scope.activity;
  $scope.mtaAlert;
  $scope.temp;
  $scope.city;
  $scope.time;
  $scope.weatherEvent;

  $scope.getFoodTerm = function() {
    Food.postFoodPlaces($scope.food[1])
        console.log($scope.food[1])
     $location.path('/food');
    return $scope.food[1]
  };

  $scope.getActivityTerm = function() {
    Activities.getActivities($scope.activity[1]);
    $location.path('/activities');
    return $scope.activity[1];
  };

  function timeNow() {
    var d = new Date(),
        h = (d.getHours()<10?'0':'') + d.getHours(),
        m = (d.getMinutes()<10?'0':'') + d.getMinutes();
    return h + ' : ' + m;
  }

  var init = function () {
    goGet.getWeatherData()
      .then(function (data) {
        weatherData = data.data;
        display(weatherData);
        setInterval(display.bind(null, weatherData), 5000);
      })
      .catch(function (error) {
        console.error(error);
      });

  };

  var display = function(data) {
    positionSunMoon();
    $scope.$apply(function() {
      $scope.weatherEvent = data.weatherEvent;
      var skycons = new Skycons({"color": "white"});
      skycons.set(data.weatherEvent, data.weatherEvent);
      skycons.play();
      $scope.phrase = data.phrases[Math.floor(Math.random() * data.phrases.length)];
      $scope.food = data.foods[Math.floor(Math.random() * data.foods.length)].split(":");
      $scope.foodTips = "Find Nearest"

      $scope.prop = data.props[Math.floor(Math.random() * data.props.length)];
      $scope.activity = data.activity[Math.floor(Math.random() * data.activity.length)].split(":");

      $scope.tips = "Find Nearest";

      $scope.temp = data.temperature.toFixed(1) + " ℉";
      $scope.city = data.timezone.split("/")[1].split("_").join(" ");
      $scope.time = timeNow();

      $scope.mtaAlert = data.subwayInfo.length === 0 ? ["All Good!"] : data.subwayInfo;

    });
  }

  var positionSunMoon = function() {
    var d = new Date();
    var minutes = d.getHours() * 60 +  d.getMinutes() - (6 * 60);
    var rad = 2 * Math.PI * minutes / 1440
    var top = Math.sin(Math.PI - rad) * (window.innerHeight)
    var left = Math.cos(Math.PI - rad) * (window.innerHeight)

    if(document.getElementsByClassName("positionSun")[0] !== undefined) {
      var sunStyle = document.getElementsByClassName("positionSun")[0].style;
      sunStyle.top = window.innerHeight -150 - top + "px";
      sunStyle.left = (window.innerWidth / 2) - 150 + left + "px";

      var moonStyle = document.getElementsByClassName("positionMoon")[0].style;
      moonStyle.top = window.innerHeight - 150 + top + "px";
      moonStyle.left = (window.innerWidth / 2) - 150 - left + "px";
   }
  }

  init();
})<commit_msg>small fixes<commit_after>angular.module('chattyWeather.weather', [])

.controller('WeatherController', function($scope, goGet, $http, $location, Activities, Food) {
	var weatherData;
  $scope.phrase = ". . loading . .";
  $scope.food;
  $scope.prop;
  $scope.activity;
  $scope.mtaAlert;
  $scope.temp;
  $scope.city;
  $scope.time;
  $scope.weatherEvent;

  $scope.getFoodTerm = function() {
    Food.postFoodPlaces($scope.food[1])
        console.log($scope.food[1])
     $location.path('/food');
    return $scope.food[1]
  };

  $scope.getActivityTerm = function() {
    Activities.getActivities($scope.activity[1]);
    $location.path('/activities');
    return $scope.activity[1];
  };

  function timeNow() {
    var d = new Date(),
        h = (d.getHours()<10?'0':'') + d.getHours(),
        m = (d.getMinutes()<10?'0':'') + d.getMinutes();
    return h + ' : ' + m;
  }

  var init = function () {
    goGet.getWeatherData()
      .then(function (data) {
        weatherData = data.data;
        display(weatherData);
        setInterval(display.bind(null, weatherData), 5000);
      })
      .catch(function (error) {
        console.error(error);
      });

  };

  var display = function(data) {
    positionSunMoon();
    $scope.$apply(function() {
      $scope.weatherEvent = data.weatherEvent;
      var skycons = new Skycons({"color": "white"});
      skycons.set(data.weatherEvent, data.weatherEvent);
      skycons.play();
      $scope.phrase = data.phrases[Math.floor(Math.random() * data.phrases.length)];
      $scope.food = data.foods[Math.floor(Math.random() * data.foods.length)].split(":");

      $scope.prop = data.props[Math.floor(Math.random() * data.props.length)];
      $scope.activity = data.activity[Math.floor(Math.random() * data.activity.length)].split(":");

      $scope.temp = data.temperature.toFixed(1) + " ℉";
      $scope.city = data.timezone.split("/")[1].split("_").join(" ");
      $scope.time = timeNow();

      $scope.mtaAlert = data.subwayInfo.length === 0 ? ["All Good!"] : data.subwayInfo;

    });
  }

  var positionSunMoon = function() {
    var d = new Date();
    var minutes = d.getHours() * 60 +  d.getMinutes() - (6 * 60);
    var rad = 2 * Math.PI * minutes / 1440
    var top = Math.sin(Math.PI - rad) * (window.innerHeight)
    var left = Math.cos(Math.PI - rad) * (window.innerHeight)

    if(document.getElementsByClassName("positionSun")[0] !== undefined) {
      var sunStyle = document.getElementsByClassName("positionSun")[0].style;
      sunStyle.top = window.innerHeight -150 - top + "px";
      sunStyle.left = (window.innerWidth / 2) - 150 + left + "px";

      var moonStyle = document.getElementsByClassName("positionMoon")[0].style;
      moonStyle.top = window.innerHeight - 150 + top + "px";
      moonStyle.left = (window.innerWidth / 2) - 150 - left + "px";
   }
  }

  init();
})<|endoftext|>


<commit_before>let app     = require('../../../index.js');
let discord = require('discord.js-commando');
let logger  = app.logger;

module.exports = class CoinsCommand extends discord.Command {
	constructor(client) {
		super(client, {
			name: 'coins',
			aliases: ['bits'],
			group: 'everyone',
			memberName: 'coins',
			description: 'Zeigt deine aktuelle Anzahl an Coins/Bits an',
			throttling: {
				usages: 3,
				duration: 60
			}
		});
	}

	async run(msg, args) {
		app.services.brg.getCommunityUserCoins(msg.author.id)
			.then(function(response) {
				let richEmbed = { embed: {
					color: 6360082,
					title: '**Dein aktueller Kontostand**\n\n',
					description: ':moneybag: ' + response.data.result.coins + ' Bits'
				}};

				return msg.channel.send('', richEmbed);
			})
			.catch(function(error) {
				logger.error(error);
				return msg.reply('Sorry, es gab einen Fehler beim ausführen des Befehls.\nhttps://derpicdn.net/img/2012/6/20/10898/full.gif');
			});
	}
};
<commit_msg>API changes<commit_after>let app     = require('../../../index.js');
let discord = require('discord.js-commando');
let logger  = app.logger;

module.exports = class CoinsCommand extends discord.Command {
	constructor(client) {
		super(client, {
			name: 'coins',
			aliases: ['bits'],
			group: 'everyone',
			memberName: 'coins',
			description: 'Zeigt deine aktuelle Anzahl an Coins/Bits an',
			throttling: {
				usages: 3,
				duration: 60
			}
		});
	}

	async run(msg, args) {
		app.services.brg.getCommunityUserCoins(msg.author.id)
			.then(function(response) {
				let richEmbed = { embed: {
					color: 6360082,
					title: '**Dein aktueller Kontostand**\n\n',
					description: ':moneybag: ' + response.result.coins + ' Bits'
				}};

				return msg.channel.send('', richEmbed);
			})
			.catch(function(error) {
				logger.error(error);
				return msg.reply('Sorry, es gab einen Fehler beim ausführen des Befehls.\nhttps://derpicdn.net/img/2012/6/20/10898/full.gif');
			});
	}
};
<|endoftext|>


<commit_before>import React, { PropTypes, Component } from 'react'
import { Link } from 'react-router'
import { connect } from 'react-redux'
import { fetchSearch } from '../actions'

const mapStateToProps = state => {
  const { node: { entityCount, isFetching, title, superEdges, queryLink, canonicalLink  } } = state

  return {
    entityCount,
    title,
    isFetching,
    superEdges,
    queryLink,
    canonicalLink,
  }
}

class Connections extends Component {
  static propTypes = {
    dispatch: PropTypes.func.isRequired,
    entityCount: PropTypes.number.isRequired,
    superEdges: PropTypes.array.isRequired,
    title: PropTypes.string.isRequired,
    queryLink: PropTypes.string.isRequired,
    canonicalLink: PropTypes.string.isRequired,
  }

  componentDidMount() {
    const { dispatch } = this.props
    chrome.tabs.query({
      active: true,
      currentWindow: true
    }, function(tabs) {
      const url = tabs[0].url.split('?')[0]
      dispatch(fetchSearch(url))
    });
  }

  goToWikiWeb = () => { chrome.tabs.update(null, {url:'https://wikiweb.org'}); };

  render() {
    const { entityCount, title, superEdges, queryLink, canonicalLink } = this.props;

    /* Connections */
    const edgeCardsJSX = (

        {superEdges.map((card, index) => {
          return (

{card.entity.title}

{card.entity.canonicalLink}

                @{card.edges[0].user.username}

)
          })
        }

    );

    /* Footer */
    const footerJSX = (

        <Link to="add" style={{textDecoration: 'none', color: '#4d4d4d', outline: 'none'}}>

            WikiWeb

        </Link>
        <Link to="add" style={{textDecoration: 'none', color: '#4d4d4d'}}>

            +

        </Link>

    );

    return (

        {edgeCardsJSX}
        {footerJSX}

    )
  }
}

export default connect(mapStateToProps)(Connections)
<commit_msg>font size change. pushing so I can pull<commit_after>import React, { PropTypes, Component } from 'react'
import { Link } from 'react-router'
import { connect } from 'react-redux'
import { fetchSearch } from '../actions'

const mapStateToProps = state => {
  const { node: { entityCount, isFetching, title, superEdges, queryLink, canonicalLink  } } = state

  return {
    entityCount,
    title,
    isFetching,
    superEdges,
    queryLink,
    canonicalLink,
  }
}

class Connections extends Component {
  static propTypes = {
    dispatch: PropTypes.func.isRequired,
    entityCount: PropTypes.number.isRequired,
    superEdges: PropTypes.array.isRequired,
    title: PropTypes.string.isRequired,
    queryLink: PropTypes.string.isRequired,
    canonicalLink: PropTypes.string.isRequired,
  }

  componentDidMount() {
    const { dispatch } = this.props
    chrome.tabs.query({
      active: true,
      currentWindow: true
    }, function(tabs) {
      const url = tabs[0].url.split('?')[0]
      dispatch(fetchSearch(url))
    });
  }

  goToWikiWeb = () => { chrome.tabs.update(null, {url:'https://wikiweb.org'}); };

  render() {
    const { entityCount, title, superEdges, queryLink, canonicalLink } = this.props;

    /* Connections */
    const edgeCardsJSX = (

        {superEdges.map((card, index) => {
          return (

{card.entity.title}

{card.entity.canonicalLink}

                @{card.edges[0].user.username}

)
          })
        }

    );

    /* Footer */
    const footerJSX = (

        <Link to="add" style={{textDecoration: 'none', color: '#4d4d4d', outline: 'none'}}>

            WikiWeb

        </Link>
        <Link to="add" style={{textDecoration: 'none', color: '#4d4d4d'}}>

            +

        </Link>

    );

    return (

        {edgeCardsJSX}
        {footerJSX}

    )
  }
}

export default connect(mapStateToProps)(Connections)
<|endoftext|>


<commit_before>import Ember from 'ember';
// import $ from 'jquery';

export default Ember.Component.extend({
  expense: {
    sum: '',
    category: '',
    name: ''
  },
  currency: '£',
  expenseCategories: [
    'Charity',
    'Clothing',
    'Education',
    'Events',
    'Food',
    'Gifts',
    'Healthcare',
    'Household',
    'Leisure',
    'Hobbies',
    'Trasportation',
    'Utilities',
    'Vacation'
  ],

  errorMessagesSum: {
    emRequired: 'This field can\'t be blank',
    emPattern: 'Must be a number!'
  },

  errorMessagesCategory: {
    emRequired: 'Must select a category'
  },

  init () {
    this._super();
    Ember.TextSupport.reopen({
      attributeBindings: ['em-required', 'em-min', 'em-max', 'em-pattern']
    });
  },

  didInsertElement () {
    componentHandler.upgradeAllRegistered();
  },

  actions: {
    clearInputs () {
      this.set('expense', {
        sum: '',
        category: '',
        name: ''
      });
      this.$('.mdl-textfield').removeClass('is-dirty is-invalid is-touched');
    },
    addExpense () {
      Ember.run.later(() => {
        if (!this.$().find('.is-invalid').length) {
          this.sendAction('action', this.get('expense'));
          this.send('clearInputs');
        }
      }, 200);
    }
  }
});
<commit_msg>refactor: Change expenses chart title<commit_after>import Ember from 'ember';
// import $ from 'jquery';

export default Ember.Component.extend({
  expense: {
    sum: '',
    category: '',
    name: ''
  },
  currency: '£',
  expenseCategories: [
    'Charity',
    'Clothing',
    'Education',
    'Events',
    'Food',
    'Gifts',
    'Healthcare',
    'Household',
    'Leisure',
    'Hobbies',
    'Trasportation',
    'Utilities',
    'Vacation'
  ],

  errorMessagesSum: {
    emRequired: 'This field can\'t be blank',
    emPattern: 'Must be a number!'
  },

  errorMessagesCategory: {
    emRequired: 'Select or add your own category'
  },

  init () {
    this._super();
    Ember.TextSupport.reopen({
      attributeBindings: ['em-required', 'em-min', 'em-max', 'em-pattern']
    });
  },

  didInsertElement () {
    componentHandler.upgradeAllRegistered();
  },

  actions: {
    clearInputs () {
      this.set('expense', {
        sum: '',
        category: '',
        name: ''
      });
      this.$('.mdl-textfield').removeClass('is-dirty is-invalid is-touched');
    },
    addExpense () {
      Ember.run.later(() => {
        if (!this.$().find('.is-invalid').length) {
          this.sendAction('action', this.get('expense'));
          this.send('clearInputs');
        }
      }, 200);
    }
  }
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import HorizontalBar from '../components/horizontal-bar';

const translation = function(x,y) {
  return 'translate(' + x + ',' + y + ')';
};

export default HorizontalBar.extend({
  margin: {
    top: 20,
    right: 20,
    bottom: 24,
    left: 20,
    middle: 28,
  },
  height: 300,
  debouncedDidResize() {
    this._super(...arguments);
    this.get('svg').remove();
    this.set('svg', null);
    this.createChart();
  },

  createChart: function createChart() {
    let svg = this.get('svg');
    const margin = this.get('margin');
    const el = this.$();
    const elWidth = el.width();
    const height = this.get('height') - margin.top - margin.bottom;
    const width = elWidth - margin.left - margin.right;

    if (!svg) {
      const el = this.$();
      svg = d3.select(el.get(0)).append('svg')
        .attr('class', 'age-chart')
        .attr('width', margin.left + width + margin.right)
        .attr('height', margin.top + height + margin.bottom)
        .append('g')
          .attr('transform', translation(margin.left, margin.top));

      svg.append('g')
        .attr('class', 'male');

      svg.append('g')
        .attr('class', 'female');
    }

    this.set('svg', svg);
    this.updateChart();
  },

  updateChart() {
    const svg = this.get('svg');
    const data = this.get('data');

    const el = this.$();
    const elWidth = el.width();

    const margin = this.get('margin');

    const height = this.get('height') - margin.top - margin.bottom;
    const width = elWidth - margin.left - margin.right;

    const regionWidth = (width / 2) - margin.middle;
    const pointA = regionWidth;
    const pointB = width - regionWidth;

    const percentage = function(d) { return d; };

    svg
      .attr('width', margin.left + width + margin.right)
      .attr('height', margin.top + height + margin.bottom);

    const maxValue = Math.max(
      d3.max(data, function(d) { return percentage(d.male); }),
      d3.max(data, function(d) { return percentage(d.female); }),
    );

    const xScale = d3.scaleLinear()
      .domain([0, maxValue])
      .range([0, regionWidth])
      .nice();

    const yScale = d3.scaleBand()
      .domain(data.map(function(d) { return d.group; }))
      .range([height, 0], 0.1);

    const yAxisLeft = d3.axisRight()
      .scale(yScale)
      .tickSize(4, 0)
      .tickPadding(margin.middle - 4);

    const yAxisRight = d3.axisLeft()
      .scale(yScale)
      .tickSize(4, 0)
      .tickFormat('');

    const xAxisRight = d3.axisBottom()
      .scale(xScale)
      .tickFormat('');

    const xAxisLeft = d3.axisBottom()
      .scale(xScale.copy().range([pointA, 0]))
      .tickFormat('');

    const leftBarGroup = svg.select('.male')
      .attr('transform', `${translation(pointA, 0)}scale(-1,1)`)
      .selectAll('.bar.left')
      .data(data, d => d.group);

    const rightBarGroup = svg.select('.female')
      .attr('transform', translation(pointB, 0))
      .selectAll('.bar.right')
      .data(data, d => d.group);

    // DRAW AXES
    svg.append('g')
      .attr('class', 'axis y left')
      .attr('transform', translation(pointA, 0))
      .call(yAxisLeft)
      .selectAll('text')
      .style('text-anchor', 'middle');

    svg.append('g')
      .attr('class', 'axis y right')
      .attr('transform', translation(pointB, 0))
      .call(yAxisRight);

    svg.append('g')
      .attr('class', 'axis x left')
      .attr('transform', translation(0, height))
      .call(xAxisLeft);

    svg.append('g')
      .attr('class', 'axis x right')
      .attr('transform', translation(pointB, height))
      .call(xAxisRight);

    leftBarGroup.enter()
      .append('rect')
      .attr('class', 'bar left')
      .attr('x', 0)
      .attr('y', function(d) { return yScale(d.group); })
      .attr('height', yScale.step() - 3)
      .attr('width', function(d) { return xScale(percentage(d.male)); })
      .attr('rx', 2)
      .attr('ry', 2);

    leftBarGroup.transition().duration(300)
      .attr('y', function(d) { return yScale(d.group); })
      .attr('width', function(d) { return xScale(percentage(d.male)); })
      .attr('height', yScale.step() - 3);

    rightBarGroup
      .enter().append('rect')
      .attr('class', 'bar right')
      .attr('x', 0)
      .attr('y', function(d) { return yScale(d.group); })
      .attr('width', function(d) { return xScale(percentage(d.female)); })
      .attr('height', yScale.step() - 3);

    rightBarGroup.transition().duration(300)
      .attr('y', function(d) { return yScale(d.group); })
      .attr('width', function(d) { return xScale(percentage(d.female)); })
      .attr('height', yScale.step() - 3);

    leftBarGroup.exit().remove();
    rightBarGroup.exit().remove();
  },
});
<commit_msg>Responsive Axes<commit_after>import Ember from 'ember';
import HorizontalBar from '../components/horizontal-bar';

const translation = function(x,y) {
  return 'translate(' + x + ',' + y + ')';
};

export default HorizontalBar.extend({
  margin: {
    top: 20,
    right: 20,
    bottom: 24,
    left: 20,
    middle: 28,
  },
  height: 300,

  createChart: function createChart() {
    let svg = this.get('svg');
    const margin = this.get('margin');
    const el = this.$();
    const elWidth = el.width();
    const height = this.get('height') - margin.top - margin.bottom;
    const width = elWidth - margin.left - margin.right;

    if (!svg) {
      svg = d3.select(el.get(0)).append('svg')
        .attr('class', 'age-chart')
        .attr('width', margin.left + width + margin.right)
        .attr('height', margin.top + height + margin.bottom)
        .append('g')
        .attr('class', 'padding-group')
        .attr('transform', translation(margin.left, margin.top));

      svg.append('g')
        .attr('class', 'male');

      svg.append('g')
        .attr('class', 'female');

      svg.append('g')
        .attr('class', 'axis x-axis-left');

      svg.append('g')
        .attr('class', 'axis x-axis-right');

      svg.append('g')
        .attr('class', 'axis y-axis-left');
    }

    this.set('svg', svg);
    this.updateChart();
  },

  updateChart() {
    const svg = this.get('svg');
    const data = this.get('data');

    const el = this.$();
    const elWidth = el.width();

    const margin = this.get('margin');

    const height = this.get('height') - margin.top - margin.bottom;
    const width = elWidth - margin.left - margin.right;

    const regionWidth = (width / 2) - margin.middle;
    const pointA = regionWidth;
    const pointB = width - regionWidth;

    const percentage = function(d) { return d; };

    svg
      .attr('width', margin.left + width + margin.right)
      .attr('height', margin.top + height + margin.bottom);

    svg.select('.padding-group')
      .attr('transform', translation(margin.left, margin.top));

    const maxValue = Math.max(
      d3.max(data, function(d) { return percentage(d.male); }),
      d3.max(data, function(d) { return percentage(d.female); }),
    );

    const xScale = d3.scaleLinear()
      .domain([0, maxValue])
      .range([0, regionWidth])
      .nice();

    const yScale = d3.scaleBand()
      .domain(data.map(function(d) { return d.group; }))
      .range([height, 0], 0.1);

    const yAxisLeft = d3.axisRight()
      .scale(yScale)
      .tickSize(4, 0)
      .tickPadding(margin.middle - 4)
      .tickFormat(d => `${d.replace('_', ' - ')}`);

    const xAxisRight = d3.axisBottom()
      .scale(xScale)
      .ticks(4)
      .tickFormat(d => `${d}%`);

    const xAxisLeft = d3.axisBottom()
      .scale(xScale.copy().range([pointA, 0]))
      .ticks(4)
      .tickFormat(d => `${d}%`);

    const leftBarGroup = svg.select('.male')
      .attr('transform', `${translation(pointA, 0)}scale(-1,1)`)
      .selectAll('.bar.left')
      .data(data, d => d.group);

    const rightBarGroup = svg.select('.female')
      .attr('transform', translation(pointB, 0))
      .selectAll('.bar.right')
      .data(data, d => d.group);

    // DRAW AXES
    svg.select('.y-axis-left')
      .attr('transform', translation(pointA, 0))
      .call(yAxisLeft)
      .selectAll('text')
      .style('text-anchor', 'middle');

    svg.select('.x-axis-left')
      .attr('transform', translation(0, height))
      .call(xAxisLeft);

    svg.select('.x-axis-right')
      .attr('transform', translation(pointB, height))
      .call(xAxisRight);

    leftBarGroup.enter()
      .append('rect')
      .attr('class', 'bar left')
      .attr('x', 0)
      .attr('y', function(d) { return yScale(d.group); })
      .attr('height', yScale.step() - 3)
      .attr('width', function(d) { return xScale(percentage(d.male)); })
      .attr('rx', 2)
      .attr('ry', 2);

    leftBarGroup.transition().duration(300)
      .attr('y', function(d) { return yScale(d.group); })
      .attr('width', function(d) { return xScale(percentage(d.male)); })
      .attr('height', yScale.step() - 3);

    rightBarGroup
      .enter().append('rect')
      .attr('class', 'bar right')
      .attr('x', 0)
      .attr('y', function(d) { return yScale(d.group); })
      .attr('width', function(d) { return xScale(percentage(d.female)); })
      .attr('height', yScale.step() - 3);

    rightBarGroup.transition().duration(300)
      .attr('y', function(d) { return yScale(d.group); })
      .attr('width', function(d) { return xScale(percentage(d.female)); })
      .attr('height', yScale.step() - 3);

    leftBarGroup.exit().remove();
    rightBarGroup.exit().remove();
  },
});
<|endoftext|>


<commit_before>import Ember from 'ember';
/* global Chart */

export default Ember.Component.extend({
  tagName: 'canvas',
  attributeBindings: ['width', 'height'],

  renderChart: function(){
    var context = this.get('element').getContext('2d');
    var data = this.get('data');
    var type = this.get('type').classify();
    var options = Ember.merge({}, this.get('options'));

    var chart = new Chart(context)[type](data, options);

    if (this.get('legend')) {
      var legend = chart.generateLegend();
      this.$().parent().append(legend);
    };

    this.set('chart', chart);
  }.on('didInsertElement'),

  destroyChart: function(){
    this.get('chart').destroy();
  }.on('willDestroyElement'),

  updateChart: function(){
    this.destroyChart();
    this.renderChart();
  }.observes('data', 'options')
});<commit_msg>UpdateChart removesChart unnecessary<commit_after>import Ember from 'ember';
/* global Chart */

export default Ember.Component.extend({
  tagName: 'canvas',
  attributeBindings: ['width', 'height'],

  renderChart: function(){
    var context = this.get('element').getContext('2d');
    var data = this.get('data');
    var type = this.get('type').classify();
    var options = Ember.merge({}, this.get('options'));

    var chart = new Chart(context)[type](data, options);

    if (this.get('legend')) {
      var legend = chart.generateLegend();
      this.$().parent().append(legend);
    };

    this.set('chart', chart);
  }.on('didInsertElement'),

  destroyChart: function(){
    this.get('chart').destroy();
  }.on('willDestroyElement'),

  updateChart: function(){
    try {
    	var self = this;
    	this.get('data.datasets').forEach(function(dataset, i) {
    		dataset.data.forEach(function(item, j) {
    			self.get('chart').datasets[i].points[j].value = item;
    		});
    	});
    	this.get('chart').update();
    } catch(error) {
    	Ember.warn('Dataset is not equal in structure as previous values. Rebuilding chart...');
    	this.destroyChart();
    	this.renderChart();
    }
  }.observes('data', 'options')
});
<|endoftext|>


<commit_before>/**
 * @name logcafe.js
 * @author Kei Funagayama <funagayama_kei@cyberagent.co.jp>
 * copyright (c) Cyberagent Inc.
 * @overview browser logging.
 */

(function (global) {
    'use strict';

    /**
     * Empty function
     * @function
     * @private
     */
    var none = function none() {};

    /**
     * Logger class
     * @class
     * @name Logger
     */
    var Logger = function Logger(category, config) {
        this.initialize(category, config);
    };

    Logger.prototype = {
        /**
         * Logger constructor
         * @param {String} category
         * @param {JSON} config config data
         * @memberof Logger
         * @instance
         */
        initialize: function initialize(category, config) {
            this.category = category;
            this.config = config;
            this.level = this.config.level;

            if (this.config.separator) {
                this.separator = this.config.separator || ' ';
            }

            if (this.level === this.LEVELS.TRACE) {
                // pass
            } else if (this.level === this.LEVELS.DEBUG) {
                this.trace = none;
            } else if (this.level === this.LEVELS.INFO) {
                this.trace = this.debug = none;
            } else if (this.level === this.LEVELS.WARN) {
                this.trace = this.debug = this.info = none;
            } else if (this.level === this.LEVELS.ERROR) {
                this.trace = this.debug = this.info = this.warn = none;
            } else {
                // pass
            }
        },

        /**
         * Log level
         * @const {string} LEVELS
         * @memberOf Logger
         */
        LEVELS: {
            'OFF': 'OFF',
            'TRACE': 'TRACE',
            'DEBUG': 'DEBUG',
            'INFO': 'INFO',
            'WARN': 'WARN',
            'ERROR': 'ERROR'
        },

        /**
         * Exclude category forward match
         * @memberOf Logger
         * @instance
         * @function
         * @private
         */
        _exclude: function _exclude() {
            if (this.config.excludes && 0 < this.config.excludes.length) {
                for (var i = 0; i < this.config.excludes.length; i++) {
                    var reg = new RegExp('^' + this.config.excludes[i]);
                    if (this.category.match(reg)) {
                        return true;
                    }
                }
            }
            return false;
        },

        /**
         * trace method
         * @memberOf Logger
         * @instance
         * @function
         */
        trace: function trace() {
            !this._exclude() && console.debug(this.output('trace', arguments));
        },

        /**
         * debug output method
         * @memberOf Logger
         * @instance
         * @function
         */
        debug: function debug() {
            !this._exclude() && console.debug(this.output('debug', arguments));
        },

        /**
         * info output method
         * @memberOf Logger
         * @instance
         * @function
         */
        info : function info() {
            !this._exclude() && console.info(this.output('info', arguments));
        },

        /**
         * warn output method
         * @instance
         * @memberOf Logger
         * @function
         */
        warn : function warn() {
            !this._exclude() && console.warn(this.output('warn', arguments));
        },

        /**
         * error output method
         * @instance
         * @memberOf Logger
         * @function
         */
        error: function error() {
            !this._exclude() && console.error(this.output('error', arguments));
        },

        /**
         * Generates a log record.
         * @memberof Logger
         * @instance
         * @function
         * @param {String} level log level
         * @param {Array} _arguments log datas
         * @return {String}
         */
        output: function output(level, _arguments) {
            var args = Array.prototype.slice.call(_arguments);

            for (var i = 0; i < args.length; i++) {
                if (args[i] === undefined) {
                    args[i] = '"undefined"';
                } else if (args[i] === null) {
                    args[i] = '"null"';
                } else if ((args[i] instanceof Error) || (args[i].constructor.name === 'Error')) {
                    var err = args[i];
                    err.stack ? args[i] = err.stack : args[i] = err.message;
                } else if (typeof args[i] === 'object') {
                    args[i] = args[i].constructor.name + ':' + JSON.stringify(args[i]);
                }
            }

            var suffix = '';
            var stack = new Error().stack;
            var lines, line, idx;
            if (stack) {
                lines = stack.split('\n');
                if (lines[3]) {
                    line = lines[3];
                    idx = line.indexOf('(');
                    if (idx >= 0) {
                        suffix = line.substring(idx);
                        if (suffix.charAt(suffix.length - 1) !== ')') {
                            suffix = '(' + suffix + ')';
                        }
                    } else {
                        suffix = '(' + line.replace(/[ ]*at /, '') + ')';
                    }
                } else if (lines[2]) {
                    line = lines[2];
                    idx = line.indexOf('@');
                    if (idx >= 0) {
                        suffix = line.substring(idx + 1);
                        suffix = ' (' + suffix + ')';
                    }

                }
            }

            return '[' + level + '][' + this.category + '] ' + args.join(this.separator) + ' ' + suffix;
        }
    };

    /**
     * Logging model
     * @class
     * @name LogCafe
     */
    var LogCafe = function LogCafe(config) {
        this.initialize(config);
    };
    LogCafe.prototype = {
        /**
         * Logging model
         * @memberof LogCafe
         * @instance
         */
        initialize: function initialize(config) {
            this.config = config;
            this.loggers = {};
        },

        /**
         * Setting up a configuration file.
         * @memberof LogCafe
         * @instance
         * @function
         * @public
         * @param {JSON} config config data
         */
        setConfigure: function setConfigure(config) {
            this.config = config;
            return this;
        },

        /**
         * Get Logger
         * @memberof LogCafe
         * @instance
         * @function
         * @public
         * @param {String} category
         * @return {Logger}
         */
        getLogger: function getLogger(category) {
            if (this.loggers[category]) {
                return this.loggers[category];
            }
            this.loggers[category] = new Logger(category, this.config);
            return this.loggers[category];

        }
    };

        /**
         * Version
         * @memberof LogCafe
         * @public
         */
    LogCafe.VERSION = '0.6.7';

    if (typeof define === 'function' && define.amd) {
        // requirejs
        define(function (require, exports, module) {
            return LogCafe;
        });
    } else if (typeof module !== 'undefined' && module.exports) {
        // node
        module.exports = LogCafe;
    } else {
        // others, export global
        global.LogCafe = LogCafe;
    }
})(this);
<commit_msg>add missing return doc<commit_after>/**
 * @name logcafe.js
 * @author Kei Funagayama <funagayama_kei@cyberagent.co.jp>
 * copyright (c) Cyberagent Inc.
 * @overview browser logging.
 */

(function (global) {
    'use strict';

    /**
     * Empty function
     * @function
     * @private
     */
    var none = function none() {};

    /**
     * Logger class
     * @class
     * @name Logger
     */
    var Logger = function Logger(category, config) {
        this.initialize(category, config);
    };

    Logger.prototype = {
        /**
         * Logger constructor
         * @param {String} category
         * @param {JSON} config config data
         * @memberof Logger
         * @instance
         */
        initialize: function initialize(category, config) {
            this.category = category;
            this.config = config;
            this.level = this.config.level;

            if (this.config.separator) {
                this.separator = this.config.separator || ' ';
            }

            if (this.level === this.LEVELS.TRACE) {
                // pass
            } else if (this.level === this.LEVELS.DEBUG) {
                this.trace = none;
            } else if (this.level === this.LEVELS.INFO) {
                this.trace = this.debug = none;
            } else if (this.level === this.LEVELS.WARN) {
                this.trace = this.debug = this.info = none;
            } else if (this.level === this.LEVELS.ERROR) {
                this.trace = this.debug = this.info = this.warn = none;
            } else {
                // pass
            }
        },

        /**
         * Log level
         * @const {string} LEVELS
         * @memberOf Logger
         */
        LEVELS: {
            'OFF': 'OFF',
            'TRACE': 'TRACE',
            'DEBUG': 'DEBUG',
            'INFO': 'INFO',
            'WARN': 'WARN',
            'ERROR': 'ERROR'
        },

        /**
         * Exclude category forward match
         * @memberOf Logger
         * @instance
         * @function
         * @private
         * @return {Boolean}
         */
        _exclude: function _exclude() {
            if (this.config.excludes && 0 < this.config.excludes.length) {
                for (var i = 0; i < this.config.excludes.length; i++) {
                    var reg = new RegExp('^' + this.config.excludes[i]);
                    if (this.category.match(reg)) {
                        return true;
                    }
                }
            }
            return false;
        },

        /**
         * trace method
         * @memberOf Logger
         * @instance
         * @function
         */
        trace: function trace() {
            !this._exclude() && console.debug(this.output('trace', arguments));
        },

        /**
         * debug output method
         * @memberOf Logger
         * @instance
         * @function
         */
        debug: function debug() {
            !this._exclude() && console.debug(this.output('debug', arguments));
        },

        /**
         * info output method
         * @memberOf Logger
         * @instance
         * @function
         */
        info : function info() {
            !this._exclude() && console.info(this.output('info', arguments));
        },

        /**
         * warn output method
         * @instance
         * @memberOf Logger
         * @function
         */
        warn : function warn() {
            !this._exclude() && console.warn(this.output('warn', arguments));
        },

        /**
         * error output method
         * @instance
         * @memberOf Logger
         * @function
         */
        error: function error() {
            !this._exclude() && console.error(this.output('error', arguments));
        },

        /**
         * Generates a log record.
         * @memberof Logger
         * @instance
         * @function
         * @param {String} level log level
         * @param {Array} _arguments log datas
         * @return {String}
         */
        output: function output(level, _arguments) {
            var args = Array.prototype.slice.call(_arguments);

            for (var i = 0; i < args.length; i++) {
                if (args[i] === undefined) {
                    args[i] = '"undefined"';
                } else if (args[i] === null) {
                    args[i] = '"null"';
                } else if ((args[i] instanceof Error) || (args[i].constructor.name === 'Error')) {
                    var err = args[i];
                    err.stack ? args[i] = err.stack : args[i] = err.message;
                } else if (typeof args[i] === 'object') {
                    args[i] = args[i].constructor.name + ':' + JSON.stringify(args[i]);
                }
            }

            var suffix = '';
            var stack = new Error().stack;
            var lines, line, idx;
            if (stack) {
                lines = stack.split('\n');
                if (lines[3]) {
                    line = lines[3];
                    idx = line.indexOf('(');
                    if (idx >= 0) {
                        suffix = line.substring(idx);
                        if (suffix.charAt(suffix.length - 1) !== ')') {
                            suffix = '(' + suffix + ')';
                        }
                    } else {
                        suffix = '(' + line.replace(/[ ]*at /, '') + ')';
                    }
                } else if (lines[2]) {
                    line = lines[2];
                    idx = line.indexOf('@');
                    if (idx >= 0) {
                        suffix = line.substring(idx + 1);
                        suffix = ' (' + suffix + ')';
                    }

                }
            }

            return '[' + level + '][' + this.category + '] ' + args.join(this.separator) + ' ' + suffix;
        }
    };

    /**
     * Logging model
     * @class
     * @name LogCafe
     */
    var LogCafe = function LogCafe(config) {
        this.initialize(config);
    };
    LogCafe.prototype = {
        /**
         * Logging model
         * @memberof LogCafe
         * @instance
         */
        initialize: function initialize(config) {
            this.config = config;
            this.loggers = {};
        },

        /**
         * Setting up a configuration file.
         * @memberof LogCafe
         * @instance
         * @function
         * @public
         * @param {JSON} config config data
         */
        setConfigure: function setConfigure(config) {
            this.config = config;
            return this;
        },

        /**
         * Get Logger
         * @memberof LogCafe
         * @instance
         * @function
         * @public
         * @param {String} category
         * @return {Logger}
         */
        getLogger: function getLogger(category) {
            if (this.loggers[category]) {
                return this.loggers[category];
            }
            this.loggers[category] = new Logger(category, this.config);
            return this.loggers[category];

        }
    };

        /**
         * Version
         * @memberof LogCafe
         * @public
         */
    LogCafe.VERSION = '0.6.7';

    if (typeof define === 'function' && define.amd) {
        // requirejs
        define(function (require, exports, module) {
            return LogCafe;
        });
    } else if (typeof module !== 'undefined' && module.exports) {
        // node
        module.exports = LogCafe;
    } else {
        // others, export global
        global.LogCafe = LogCafe;
    }
})(this);
<|endoftext|>


<commit_before>import Component from '@ember/component';
import DropdownMixin from 'ghost-admin/mixins/dropdown-mixin';
import {computed} from '@ember/object';
import {run} from '@ember/runloop';
import {inject as service} from '@ember/service';

export default Component.extend(DropdownMixin, {
    dropdown: service(),

    classNames: 'dropdown',
    classNameBindings: ['fadeIn:fade-in-scale:fade-out', 'isOpen:open:closed'],

    name: null,
    closeOnClick: false,

    // Helps track the user re-opening the menu while it's fading out.
    closing: false,

    // Helps track whether the dropdown is open or closes, or in a transition to either
    isOpen: false,

    onClose() {},

    // Managed the toggle between the fade-in and fade-out classes
    fadeIn: computed('isOpen', 'closing', function () {
        return this.isOpen && !this.closing;
    }),

    didInsertElement() {
        this._super(...arguments);

        let dropdownService = this.dropdown;
        dropdownService.on('close', this, this.close);
        dropdownService.on('toggle', this, this.toggle);

        this._animationEndHandler = run.bind(this, function (event) {
            if (event.animationName === 'fade-out' && this.closing) {
                this.set('isOpen', false);
                this.set('closing', false);
            }
        });

        this.element.addEventListener('animationend', this._animationEndHandler);
    },

    willDestroyElement() {
        this._super(...arguments);

        let dropdownService = this.dropdown;
        dropdownService.off('close', this, this.close);
        dropdownService.off('toggle', this, this.toggle);

        this.element.removeEventListener('animationend', this._animationEndHandler);
    },

    open() {
        this.set('isOpen', true);
        this.set('closing', false);
        this.set('button.isOpen', true);
    },

    close() {
        this.set('closing', true);
        this.onClose?.();
        if (this.button) {
            this.set('button.isOpen', false);
        }
    },

    // Called by the dropdown service when any dropdown button is clicked.
    toggle(options) {
        let isClosing = this.closing;
        let isOpen = this.isOpen;
        let name = this.name;
        let targetDropdownName = options.target;
        let button = this.button;

        if (name === targetDropdownName && (!isOpen || isClosing)) {
            if (!button) {
                button = options.button;
                this.set('button', button);
            }
            this.open();
        } else if (isOpen) {
            this.close();
        }
    },

    click(event) {
        this._super(event);

        if (this.closeOnClick) {
            return this.close();
        }
    }
});
<commit_msg>Refined close filter dropdown behavior<commit_after>import Component from '@ember/component';
import DropdownMixin from 'ghost-admin/mixins/dropdown-mixin';
import {computed} from '@ember/object';
import {run} from '@ember/runloop';
import {inject as service} from '@ember/service';

export default Component.extend(DropdownMixin, {
    dropdown: service(),

    classNames: 'dropdown',
    classNameBindings: ['fadeIn:fade-in-scale:fade-out', 'isOpen:open:closed'],

    name: null,
    closeOnClick: false,

    // Helps track the user re-opening the menu while it's fading out.
    closing: false,

    // Helps track whether the dropdown is open or closes, or in a transition to either
    isOpen: false,

    onClose() {},

    // Managed the toggle between the fade-in and fade-out classes
    fadeIn: computed('isOpen', 'closing', function () {
        return this.isOpen && !this.closing;
    }),

    didInsertElement() {
        this._super(...arguments);

        let dropdownService = this.dropdown;
        dropdownService.on('close', this, this.close);
        dropdownService.on('toggle', this, this.toggle);

        this._animationEndHandler = run.bind(this, function (event) {
            if (event.animationName === 'fade-out' && this.closing) {
                this.set('isOpen', false);
                this.set('closing', false);
                this.onClose?.();
            }
        });

        this.element.addEventListener('animationend', this._animationEndHandler);
    },

    willDestroyElement() {
        this._super(...arguments);

        let dropdownService = this.dropdown;
        dropdownService.off('close', this, this.close);
        dropdownService.off('toggle', this, this.toggle);

        this.element.removeEventListener('animationend', this._animationEndHandler);
    },

    open() {
        this.set('isOpen', true);
        this.set('closing', false);
        this.set('button.isOpen', true);
    },

    close() {
        this.set('closing', true);
        if (this.button) {
            this.set('button.isOpen', false);
        }
    },

    // Called by the dropdown service when any dropdown button is clicked.
    toggle(options) {
        let isClosing = this.closing;
        let isOpen = this.isOpen;
        let name = this.name;
        let targetDropdownName = options.target;
        let button = this.button;

        if (name === targetDropdownName && (!isOpen || isClosing)) {
            if (!button) {
                button = options.button;
                this.set('button', button);
            }
            this.open();
        } else if (isOpen) {
            this.close();
        }
    },

    click(event) {
        this._super(event);

        if (this.closeOnClick) {
            return this.close();
        }
    }
});
<|endoftext|>