<commit_before>var appId = process.env.APPLICATION_ID || require('../config/config.js').APPLICATION_ID;
var apiKey = process.env.APPLICATION_KEY || require('../config/config.js').APPLICATION_KEY;
var http = require('http');
var Recipe = require('./recipeModel');
var RecipePreference = require('../recipePreference/recipePreferenceModel');
var db = require('../db');

var allowedAllergyLibrary = {
  "Egg-Free": "397^Egg-Free",
  "Gluten-Free": "393^Gluten-Free",
  "Peanut-Free": "394^Peanut-Free",
  "Seafood-Free": "398^Seafood-Free",
  "Sesame-Free": "399^Sesame-Free",
  "Soy-Free": "400^Soy-Free",
  "Sulfite-Free": "401^Sulfite-Free",
  "Tree Nut-Free": "395^Tree Nut-Free",
  "Wheat-Free": "392^Wheat-Free"
};

var allowedCuisineLibrary = {
  "American": "cuisine^cuisine-american",
  "Italian": "cuisine^cuisine-italian",
  "Asian": "cuisine^cuisine-asian",
  "Mexican": "cuisine^cuisine-mexican",
  "Southern & Soul Food": "cuisine^cuisine-southern",
  "French": "cuisine^cuisine-french",
  "Indian": "cuisine^cuisine-indian",
  "Thai": "cuisine^cuisine-thai",
  "Japanese": "cuisine^cuisine-japanese",
  "Hawaiian": "cuisine^cuisine-hawaiian",
  "Swedish": "cuisine^cuisine-swedish",
};

var seedUserPreference = function (results, request, response) {
  new RecipePreference({'userId': request.body.id || 1, 'recipeId': 'Vegetarian-Cabbage-Soup-Recipezaar', 'preference': true }).save().then(function(model) {
    console.log('new recipe saved');
    getUserPreferences(results, request, response);
  })

};

var queryYummly = function (request, response) {
  //var allowedCuisine = request.body.allowedCuisine;
  var allowedAllergyList = request.body.allowedAllergy;
  // generate query for 10x meals requested by user in order to handle batch request
  var numResults = 10 * request.body.numMeals;

  //var numResults = request.body.numMeals;
  var start = request.body.additionalRequest ? request.body.totalRecipesRequested : 0;
  var queryString = "";
  var results = {};
  // add each allowed allergy to query string
  for (var key in allowedAllergyList) {
    if (allowedAllergyList[key]) {
      queryString += "&allowedAllergy[]" + allowedAllergyLibrary[key];
    }
  }
  //var query = "&allowedCuisine[]" + allowedCuisineLibrary[allowedCuisine] + "&allowedAllergy[]" + allowedAllergyLibrary[allowedAllergy] +"&requirePictures=true";
  var query =
    "http://api.yummly.com/v1/api/recipes?_app_id=" + appId +
    "&_app_key=" + apiKey +
    queryString + "&allowedCourse[]=course^course-Main Dishes" + "&requirePictures=true" +
    "&maxResult=" + numResults + "&start=" + start;

  http.get(query, function(yummlyResponse){
    var str = '';
    //console.log('Response is '+yummlyResponse.statusCode);
    yummlyResponse.on('data', function (chunk) {
      str += chunk;
    });

    yummlyResponse.on('end', function () {

      results = JSON.parse(str);
      //check acceptability of recipe before saving
      for(var i = 0; i < results.matches.length; i++){
        //had to make a call to a function to retain recipe info #async
        saveRecipe(results.matches[i]);
      }
      seedUserPreference(results.matches, request, response);
      //response.status(200).send(results);
    });
  });
};

var kNearestNeighbors = function (userPreferences, matches, request, response) {
  console.log('matches: ', matches);
  //console.log('userPreferences: ', userPreferences[0].flavors, "matches: ", matches[2].flavors);
  for (var i = 0; i < matches.length; i++) {
    var yummlyMatch = matches[i];
    var likelihood = 0;
    for (var j = 0; j < userPreferences.length; j++) {
      var sumOfSquares = 0;

      var userPreference = userPreferences[j];

      for (var key in yummlyMatch.flavors) {
        
        if (userPreference.flavors === null){
          break;
        }

        var base = yummlyMatch.flavors[key] - userPreference.flavors[key];
        sumOfSquares += Math.pow(base, 2);
      }
      var distance = Math.sqrt(sumOfSquares);<commit_msg>fix error in recipeController, working machine learning implementation with client side<commit_after>var appId = process.env.APPLICATION_ID || require('../config/config.js').APPLICATION_ID;
var apiKey = process.env.APPLICATION_KEY || require('../config/config.js').APPLICATION_KEY;
var http = require('http');
var Recipe = require('./recipeModel');
var RecipePreference = require('../recipePreference/recipePreferenceModel');
var db = require('../db');

var allowedAllergyLibrary = {
  "Egg-Free": "397^Egg-Free",
  "Gluten-Free": "393^Gluten-Free",
  "Peanut-Free": "394^Peanut-Free",
  "Seafood-Free": "398^Seafood-Free",
  "Sesame-Free": "399^Sesame-Free",
  "Soy-Free": "400^Soy-Free",
  "Sulfite-Free": "401^Sulfite-Free",
  "Tree Nut-Free": "395^Tree Nut-Free",
  "Wheat-Free": "392^Wheat-Free"
};

var allowedCuisineLibrary = {
  "American": "cuisine^cuisine-american",
  "Italian": "cuisine^cuisine-italian",
  "Asian": "cuisine^cuisine-asian",
  "Mexican": "cuisine^cuisine-mexican",
  "Southern & Soul Food": "cuisine^cuisine-southern",
  "French": "cuisine^cuisine-french",
  "Indian": "cuisine^cuisine-indian",
  "Thai": "cuisine^cuisine-thai",
  "Japanese": "cuisine^cuisine-japanese",
  "Hawaiian": "cuisine^cuisine-hawaiian",
  "Swedish": "cuisine^cuisine-swedish",
};

var seedUserPreference = function (results, request, response) {
  new RecipePreference({'userId': request.body.id || 1, 'recipeId': 'Vegetarian-Cabbage-Soup-Recipezaar', 'preference': true }).save().then(function(model) {
    console.log('new recipe saved');
    getUserPreferences(results, request, response);
  })

};

var queryYummly = function (request, response) {
  //var allowedCuisine = request.body.allowedCuisine;
  var allowedAllergyList = request.body.allowedAllergy;
  // generate query for 10x meals requested by user in order to handle batch request
  var numResults = 10 * request.body.numMeals;

  //var numResults = request.body.numMeals;
  var start = request.body.additionalRequest ? request.body.totalRecipesRequested : 0;
  var queryString = "";
  var results = {};
  // add each allowed allergy to query string
  for (var key in allowedAllergyList) {
    if (allowedAllergyList[key]) {
      queryString += "&allowedAllergy[]" + allowedAllergyLibrary[key];
    }
  }
  //var query = "&allowedCuisine[]" + allowedCuisineLibrary[allowedCuisine] + "&allowedAllergy[]" + allowedAllergyLibrary[allowedAllergy] +"&requirePictures=true";
  var query =
    "http://api.yummly.com/v1/api/recipes?_app_id=" + appId +
    "&_app_key=" + apiKey +
    queryString + "&allowedCourse[]=course^course-Main Dishes" + "&requirePictures=true" +
    "&maxResult=" + numResults + "&start=" + start;

  http.get(query, function(yummlyResponse){
    var str = '';
    //console.log('Response is '+yummlyResponse.statusCode);
    yummlyResponse.on('data', function (chunk) {
      str += chunk;
    });

    yummlyResponse.on('end', function () {

      results = JSON.parse(str);
      //check acceptability of recipe before saving
      for(var i = 0; i < results.matches.length; i++){
        //had to make a call to a function to retain recipe info #async
        saveRecipe(results.matches[i]);
      }
      seedUserPreference(results.matches, request, response);
      //response.status(200).send(results);
    });
  });
};

var kNearestNeighbors = function (userPreferences, matches, request, response) {
  console.log('matches: ', matches);
  //console.log('userPreferences: ', userPreferences[0].flavors, "matches: ", matches[2].flavors);
  for (var i = 0; i < matches.length; i++) {
    var yummlyMatch = matches[i];
    var likelihood = 0;
    for (var j = 0; j < userPreferences.length; j++) {
      var sumOfSquares = 0;

      var userPreference = userPreferences[j];

      for (var key in yummlyMatch.flavors) {
        
        if (userPreference.flavors === null || userPreference.flavors === undefined){
          break;
        }

        var base = yummlyMatch.flavors[key] - userPreference.flavors[key];
        sumOfSquares += Math.pow(base, 2);
      }
      var distance = Math.sqrt(sumOfSquares);
{'fraction_non_alphanumeric': 0.15761540360404838, 'fraction_numerical': 0.01110836830412244, 'mean_word_length': 4.020446096654275, 'pattern_counts': {'":': 40, '<': 9, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '502403', 'n_tokens_mistral': 2843, 'n_tokens_neox': 2672, 'n_words': 555}