问:
C++ parse date/time with microseconds
I am using strptime to parse a date and time with a specific format. The format uses the Python formatting directives, which are exactly the same as the C directives except there is an additional %f directive in Python for milliseconds defined as Microsecond as a decimal number, zero-padded on the left.. So for example:

```<code>std::tm tmb;
strptime("2010-12-30T01:20:30.0Z", "%Y-%m-%dT%H:%M:%S.%fZ", &tmb);
</code>```

This would cause a parsing error because of the %f. I cannot do a straight remove because directives like %m and %d can take either one or two digits.

Additionally, this is a problem because the %f directive can take from 1 to 6 digits. Is there a way to work around this issue?

I am working in C++, if there are any built-in functions that can help.

答:
Using Howard Hinnant's free, open-source, C++11, header-only datetime library, you can easily parse any precision you want.  You just can't put it into a tm since that is limited to seconds precision.

For example:

```<code>#include "date.h"
#include <cassert>
#include <sstream>

int
main()
{
    std::chrono::system_clock::time_point tp;
    std::istringstream ss{"2010-12-30T01:20:30.123456Z"};
    ss >> date::parse("%FT%TZ", tp);
    assert(!ss.fail());
    using namespace date;
    using namespace std::chrono_literals;
    assert(tp == sys_days(2010_y/dec/30) + 1h + 20min + 30s + 123456us);
}
</code>```

This uses C++14 chrono literals.  If you're in C++11, the last two lines would look like:

```<code>    using namespace std::chrono;
    assert(tp == sys_days(2010_y/dec/30) + hours{1} + minutes{20} +
                                           seconds{30} + microseconds{123456});
</code>```

If you're stuck with pre-<chrono> C++ (C++98/C++03), this library won't help you.

The precision of the parse is controlled by the precision of the time_point that you input into the parse function, instead of by a formatting flag.  The parse will attempt to parse as many decimal digits as your time_point will hold, but will gracefully give up if it gets less digits:

```<code>sys_time<nanoseconds> tp; // type-alias for a system_clock::time_point
                          //   with nanoseconds precision
ss >> date::parse("%FT%TZ", tp);  // still ok
</code>```

If there are more digits than needed, the parse will fail, but only because it won't see the trailing (required) Z:

```<code>sys_time<milliseconds> tp;
ss >> date::parse("%FT%TZ", tp);
assert(ss.fail());  // found "4" instead of "Z"
</code>```

If the Z hadn't been part of the format, it would have parsed "2010-12-30T01:20:30.123" into the milliseconds-precsion time_point.

This library has complete parsing and formatting facilities available, built on top of the std <chrono> library, so that you never have to deal with the ancient tm structure.  But you can convert to/from tm (at seconds precision) for communicating with other code if you need to.

"%F" is a shortcut for "%Y-%m-%d".  You can use either.

"%T" is a shortcut for "%H:%M:%S".  You can use either.

Title: C++ parse date/time with microseconds

Body:
I am using strptime to parse a date and time with a specific format. The format uses the Python formatting directives, which are exactly the same as the C directives except there is an additional %f directive in Python for milliseconds defined as Microsecond as a decimal number, zero-padded on the left.. So for example:

std::tm tmb;
strptime("2010-12-30T01:20:30.0Z", "%Y-%m-%dT%H:%M:%S.%fZ", &tmb);

This would cause a parsing error because of the %f. I cannot do a straight remove because directives like %m and %d can take either one or two digits.

Additionally, this is a problem because the %f directive can take from 1 to 6 digits. Is there a way to work around this issue?

I am working in C++, if there are any built-in functions that can help.

Body:
Using Howard Hinnant's free, open-source, C++11, header-only datetime library, you can easily parse any precision you want.  You just can't put it into a tm since that is limited to seconds precision.

For example:

#include "date.h"
#include <cassert>
#include <sstream>

int
main()
{
    std::chrono::system_clock::time_point tp;
    std::istringstream ss{"2010-12-30T01:20:30.123456Z"};
    ss >> date::parse("%FT%TZ", tp);
    assert(!ss.fail());
    using namespace date;
    using namespace std::chrono_literals;
    assert(tp == sys_days(2010_y/dec/30) + 1h + 20min + 30s + 123456us);
}

This uses C++14 chrono literals.  If you're in C++11, the last two lines would look like:

    using namespace std::chrono;
    assert(tp == sys_days(2010_y/dec/30) + hours{1} + minutes{20} +
                                           seconds{30} + microseconds{123456});

If you're stuck with pre-<chrono> C++ (C++98/C++03), this library won't help you.

The precision of the parse is controlled by the precision of the time_point that you input into the parse function, instead of by a formatting flag.  The parse will attempt to parse as many decimal digits as your time_point will hold, but will gracefully give up if it gets less digits:

sys_time<nanoseconds> tp; // type-alias for a system_clock::time_point
                          //   with nanoseconds precision
ss >> date::parse("%FT%TZ", tp);  // still ok

If there are more digits than needed, the parse will fail, but only because it won't see the trailing (required) Z:

sys_time<milliseconds> tp;
ss >> date::parse("%FT%TZ", tp);
assert(ss.fail());  // found "4" instead of "Z"

If the Z hadn't been part of the format, it would have parsed "2010-12-30T01:20:30.123" into the milliseconds-precsion time_point.

This library has complete parsing and formatting facilities available, built on top of the std <chrono> library, so that you never have to deal with the ancient tm structure.  But you can convert to/from tm (at seconds precision) for communicating with other code if you need to.

"%F" is a shortcut for "%Y-%m-%d".  You can use either.

"%T" is a shortcut for "%H:%M:%S".  You can use either.


来源: stackexchange

问:
sending code from vim to stata
I have been using Vim to write Stata scripts in Windows for a while now at the university. I am learning R at the moment, and I want to switch completely to Linux as my OS (I've recently switched to Ubuntu on my laptop). R works fine with Vim in both Windows and Linux, however I still need to use Stata sometimes. In Windows I have been using a simple AutoIt script provided by a Stata user to send lines / the whole file to stata for evaluation. This script doesnt work in Linux.

This is what the script looks like

```<code>; AutoIt v3 script to run a Stata do-file from an external text editor
; Version 3.1, Friedrich Huebler, fhuebler@gmail.com, www.huebler.info, 30 March 2009

; Declare variables
Global $ini, $statapath, $statawin, $dofile, $winpause, $keypause, $clippause

; File locations
; Path to INI file
$ini = @ScriptDir & "\rundo.ini"
; Path to Stata executable
$statapath = IniRead($ini, "Stata", "statapath", "C:\Program Files\Stata10\wsestata.exe")
; Title of Stata window
$statawin = IniRead($ini, "Stata", "statawin", "Stata/SE 10.1")

; Path to do-file that is passed to AutoIt
; Edit line to match editor used, if necessary
$dofile = $CmdLine[1]

; Delays
; Pause after copying of Stata commands to clipboard
$clippause = IniRead($ini, "Delays", "clippause", "100")
; Pause between window-related operations
$winpause = IniRead($ini, "Delays", "winpause", "200")
; Pause between keystrokes sent to Stata
$keypause = IniRead($ini, "Delays", "keypause", "1")

; Set SendKeyDelay and WinWaitDelay to speed up or slow down script
Opt("WinWaitDelay", $winpause)
Opt("SendKeyDelay", $keypause)

; If more than one Stata window is open, the window
; that was most recently active will be matched
Opt("WinTitleMatchMode", 2)

; Check if Stata is already open, start Stata if not
If WinExists($statawin) Then
  WinActivate($statawin)
  WinWaitActive($statawin)
  ; Activate Stata Command Window and select text (if any)
  Send("^4")
  Send("^a")
  ; Run saved do-file
  ; Double quotes around $dofile needed in case path contains blanks
  ClipPut("do " & '"' & $dofile & '"')
  ; Pause avoids problem with clipboard, may be AutoIt or Windows bug
  Sleep($clippause)
  Send("^v" & "{Enter}")
Else
  Run($statapath)
  WinWaitActive($statawin)
  ; Activate Stata Command Window
  Send("^4")
  ; Run saved do-file
  ; Double quotes around $dofile needed in case path contains blanks
  ClipPut("do " & '"' & $dofile & '"')
  ; Pause avoids problem with clipboard, may be AutoIt or Windows bug
  Sleep($clippause)
  Send("^v" & "{Enter}")
EndIf

; End of script
</code>```

with the following in my vimrc

```<code>" STATA DO-FILE SCRIPTS

fun! RunIt()
  w
  !start "C:\Programme\Stata10\integvim\rundo3\rundo.exe" "%:p"
endfun
map <F8> :<C-U>call RunIt()<CR><CR>
imap <F8> <Esc>:<C-U>call RunIt()<CR><CR>

fun! RunDoLines()
  let selectedLines = getbufline('%', line("'<"), line("'>"))
 if col("'>") < strlen(getline(line("'>")))
  let selectedLines[-1] = strpart(selectedLines[-1], 0, col("'>"))
  endif
 if col("'<") != 1
  let selectedLines[0] = strpart(selectedLines[0], col("'<")-1)
  endif
 let temp = tempname() . ".do"
  call writefile(selectedLines, temp)
    exec "!start C:\\Programme\\Stata10\\integvim\\rundo3\\rundo.exe " . temp
    au VimLeave * exe "!del -y" temp
endfun
map <F9> :<C-U>call RunDoLines()<CR><CR>
imap <F9> <Esc>:<C-U>call RunDoLines()<CR><CR>
</code>```

This is really practical and virtually the only reason I'm still sticking to Windows. How would I go about getting something like that for Ubuntu? I'm new to linux, and dont really know much about programming besides statistics. Any help is greatly appreciated.
(Please dont suggest emacs, emacs support for stata is faulty, and though its integration with R is much better, I would like to keep using Vim for now.)

On a possibly related topic: I'm considering learning Python, as I'll probably be working with data and doing empirical analysis for a longer time, and I think it might be useful for some tasks, e.g. to solve problems like this or parsing data from websites. Is this recommended, or should I look at another language (or forget the idea completely)?

答:
in linux you can use a plugin for vim called slime.vim which will allow you to pipe code from vim to a running R process without leaving vim. I use this on the mac for mysql, php, python and ocaml and it works great. The only caveat is that it uses screen to do its magic which is not a bad thing in itself.

If I understand your question correctly I believe this will help you enormously. Good luck and hope that helps you.

ContentLicense: CC BY-SA 3.0

Title: sending code from vim to stata

Body:
I have been using Vim to write Stata scripts in Windows for a while now at the university. I am learning R at the moment, and I want to switch completely to Linux as my OS (I've recently switched to Ubuntu on my laptop). R works fine with Vim in both Windows and Linux, however I still need to use Stata sometimes. In Windows I have been using a simple AutoIt script provided by a Stata user to send lines / the whole file to stata for evaluation. This script doesnt work in Linux.

This is what the script looks like

; AutoIt v3 script to run a Stata do-file from an external text editor
; Version 3.1, Friedrich Huebler, fhuebler@gmail.com, www.huebler.info, 30 March 2009

; Declare variables
Global $ini, $statapath, $statawin, $dofile, $winpause, $keypause, $clippause

; File locations
; Path to INI file
$ini = @ScriptDir & "\rundo.ini"
; Path to Stata executable
$statapath = IniRead($ini, "Stata", "statapath", "C:\Program Files\Stata10\wsestata.exe")
; Title of Stata window
$statawin = IniRead($ini, "Stata", "statawin", "Stata/SE 10.1")

; Path to do-file that is passed to AutoIt
; Edit line to match editor used, if necessary
$dofile = $CmdLine[1]

; Delays
; Pause after copying of Stata commands to clipboard
$clippause = IniRead($ini, "Delays", "clippause", "100")
; Pause between window-related operations
$winpause = IniRead($ini, "Delays", "winpause", "200")
; Pause between keystrokes sent to Stata
$keypause = IniRead($ini, "Delays", "keypause", "1")

; Set SendKeyDelay and WinWaitDelay to speed up or slow down script
Opt("WinWaitDelay", $winpause)
Opt("SendKeyDelay", $keypause)

; If more than one Stata window is open, the window
; that was most recently active will be matched
Opt("WinTitleMatchMode", 2)

; Check if Stata is already open, start Stata if not
If WinExists($statawin) Then
  WinActivate($statawin)
  WinWaitActive($statawin)
  ; Activate Stata Command Window and select text (if any)
  Send("^4")
  Send("^a")
  ; Run saved do-file
  ; Double quotes around $dofile needed in case path contains blanks
  ClipPut("do " & '"' & $dofile & '"')
  ; Pause avoids problem with clipboard, may be AutoIt or Windows bug
  Sleep($clippause)
  Send("^v" & "{Enter}")
Else
  Run($statapath)
  WinWaitActive($statawin)
  ; Activate Stata Command Window
  Send("^4")
  ; Run saved do-file
  ; Double quotes around $dofile needed in case path contains blanks
  ClipPut("do " & '"' & $dofile & '"')
  ; Pause avoids problem with clipboard, may be AutoIt or Windows bug
  Sleep($clippause)
  Send("^v" & "{Enter}")
EndIf

; End of script

with the following in my vimrc

" STATA DO-FILE SCRIPTS

fun! RunIt()
  w
  !start "C:\Programme\Stata10\integvim\rundo3\rundo.exe" "%:p"
endfun
map <F8> :<C-U>call RunIt()<CR><CR>
imap <F8> <Esc>:<C-U>call RunIt()<CR><CR>

fun! RunDoLines()
  let selectedLines = getbufline('%', line("'<"), line("'>"))
 if col("'>") < strlen(getline(line("'>")))
  let selectedLines[-1] = strpart(selectedLines[-1], 0, col("'>"))
  endif
 if col("'<") != 1
  let selectedLines[0] = strpart(selectedLines[0], col("'<")-1)
  endif
 let temp = tempname() . ".do"
  call writefile(selectedLines, temp)
    exec "!start C:\\Programme\\Stata10\\integvim\\rundo3\\rundo.exe " . temp
    au VimLeave * exe "!del -y" temp
endfun
map <F9> :<C-U>call RunDoLines()<CR><CR>
imap <F9> <Esc>:<C-U>call RunDoLines()<CR><CR>

This is really practical and virtually the only reason I'm still sticking to Windows. How would I go about getting something like that for Ubuntu? I'm new to linux, and dont really know much about programming besides statistics. Any help is greatly appreciated.
(Please dont suggest emacs, emacs support for stata is faulty, and though its integration with R is much better, I would like to keep using Vim for now.)

On a possibly related topic: I'm considering learning Python, as I'll probably be working with data and doing empirical analysis for a longer time, and I think it might be useful for some tasks, e.g. to solve problems like this or parsing data from websites. Is this recommended, or should I look at another language (or forget the idea completely)?

ContentLicense: CC BY-SA 2.5


问:
Trying to create an instance and multiple related instances in a many to many relationship
I am attempting to create an instance and multiple related instances with a many to many relation using a junction table.

While creating the multiple related instances, I need to add a value to a property on the junction table as well. I don't know if it is my lack of knowledge of sequelize or promises that is causing my problem.

The code I am using is below. This code does add the items to the database, but I need to redirect after the operation has completed, which is not working.

Basically, I need to create a Recipe. Once that is created, I need to create Ingredients and relate them to that Recipe. The ingredients are stored in an array coming from a form on an HTML page. While relating the Ingredients, I need to add the ingredient_quantity to the RecipeIngredients table, which is the through part of the relationship (the junction table).

```<code>global.db.Recipe.belongsToMany(
    global.db.Ingredient,
    {
        as: 'Ingredients',
        through: global.db.RecipeIngredients,
        foreignKey: 'recipe_id'
    });
global.db.Ingredient.belongsToMany(
    global.db.Recipe,
    {
        as: 'Recipes',
        through: global.db.RecipeIngredients,
        foreignKey: 'ingredient_id'
    });

router.post('/new', ensureLoggedIn, bodyParser.json(), function (req, res) {
    var recipeName = req.body.recipe_name;
    var steps = req.body.steps;
    var ingredients = req.body.ingredients;
    var ingredientQty = {};
    var currentIngredient;
    var ingredientsToAdd = [];

    db.Recipe.create({
        recipe_name: recipeName,
        directions: steps,
        FamilyId: req.user.FamilyId,
        CreatedBy: req.user._id
    })
    .then(function (recipe) {
        for (var i = 0; i < ingredients.length; i++) {

            currentIngredient = ingredients[i];
            ingredientQty[currentIngredient.ingredient_name] =
currentIngredient.quantity;

            db.Ingredient.findOrCreate({
                where: {
                    ingredient_name: currentIngredient.ingredient_name,
                    FamilyId: req.user.FamilyId
                }
            })
            .spread(function (ingredient, created) {
                if (created) {
                    console.log("Added Ingredient to DB: " +
                    currentIngredient.ingredient_name);
                }

            ingredient.Recipes = {
                ingredient_quantity:
                    ingredientQty[ingredient.ingredient_name]
            };
            ingredient.CreatedBy = req.user._id;
            recipe.addIngredient(ingredient)
            .then(function () {
                console.log("Added Ingredient " + ingredient.ingredient_name
                + " to Recipe " + recipe.recipe_name);
            });
        })
    }

})
.finally(function(recipe){
    res.redirect('/recipes');
});
});
</code>```

Any help would be greatly appreciated. I know that I am running into issues because of trying to use promises inside of a loop, I just don't know how else I can accomplish this.

答:
I was able to fix the problem that I was having. The answers here helped me come up with my solution.
I am posting the solution below in case anyone else runs into a similar issue. I created a variable to store the Promise from Recipe.create(), I used Promise.map to findOrCreate all of the ingredients from the form data. Because findOrCreate returns an array containing Promise and a boolean for if the item was created, I then had to get the actual ingredients out of the results of the Promise.map function. So I used the JavaScript array.map() function to get the first item from the arrays. And finally, use Promise.map again to add each Ingredient to the Recipe</p>

```<code>var ingredients = req.body.ingredients,
    recipeName = req.body.recipeName,
    ingredientsQty = {}; // Used to map the ingredient and quantity for the
                         // relationship, because of the Junction Table

var recipe = models.Recipe.create({recipe_name: recipeName});

// Use Promise.map to findOrCreate all ingredients from the form data
Promise.map(ingredients, function(ing){
    ingredientsQty[ing.ingredient_name] = ing.ingredient_quantity;
    return models.Ingredient.findOrCreate({ where: { ingredient_name: ing.ingredient_name}});
})

// Use JavaScript's Array.prototype.map function to return the ingredient
// instance from the array returned by findOrCreate
.then(function(results){
    return results.map(function(result){
        return result[0];
    });
})

// Return the promises for the new Recipe and Ingredients
.then(function(ingredientsInDB){
    return Promise.all([recipe, ingredientsInDB]);
})

// Now I can use Promise.map again to create the relationship between the /
// Recipe and each Ingredient
.spread(function(addedRecipe, ingredientsToAdd){
    recipe = addedRecipe;
    return Promise.map(ingredientsToAdd, function(ingredientToAdd){
        ingredientToAdd.RecipeIngredients = {
            ingredient_quantity: ingredientsQty[ingredientToAdd.ingredient_name]
        };

        return recipe.addIngredient(ingredientToAdd);
    });
})

// And here, everything is finished
.then(function(recipeWithIngredients){
   res.end
});
</code>```

Body:
I am attempting to create an instance and multiple related instances with a many to many relation using a junction table.

While creating the multiple related instances, I need to add a value to a property on the junction table as well. I don't know if it is my lack of knowledge of sequelize or promises that is causing my problem.

The code I am using is below. This code does add the items to the database, but I need to redirect after the operation has completed, which is not working.

Basically, I need to create a Recipe. Once that is created, I need to create Ingredients and relate them to that Recipe. The ingredients are stored in an array coming from a form on an HTML page. While relating the Ingredients, I need to add the ingredient_quantity to the RecipeIngredients table, which is the through part of the relationship (the junction table).

global.db.Recipe.belongsToMany(
    global.db.Ingredient,
    {
        as: 'Ingredients',
        through: global.db.RecipeIngredients,
        foreignKey: 'recipe_id'
    });
global.db.Ingredient.belongsToMany(
    global.db.Recipe,
    {
        as: 'Recipes',
        through: global.db.RecipeIngredients,
        foreignKey: 'ingredient_id'
    });

router.post('/new', ensureLoggedIn, bodyParser.json(), function (req, res) {
    var recipeName = req.body.recipe_name;
    var steps = req.body.steps;
    var ingredients = req.body.ingredients;
    var ingredientQty = {};
    var currentIngredient;
    var ingredientsToAdd = [];

    db.Recipe.create({
        recipe_name: recipeName,
        directions: steps,
        FamilyId: req.user.FamilyId,
        CreatedBy: req.user._id
    })
    .then(function (recipe) {
        for (var i = 0; i < ingredients.length; i++) {

            currentIngredient = ingredients[i];
            ingredientQty[currentIngredient.ingredient_name] =
currentIngredient.quantity;

            db.Ingredient.findOrCreate({
                where: {
                    ingredient_name: currentIngredient.ingredient_name,
                    FamilyId: req.user.FamilyId
                }
            })
            .spread(function (ingredient, created) {
                if (created) {
                    console.log("Added Ingredient to DB: " +
                    currentIngredient.ingredient_name);
                }

            ingredient.Recipes = {
                ingredient_quantity:
                    ingredientQty[ingredient.ingredient_name]
            };
            ingredient.CreatedBy = req.user._id;
            recipe.addIngredient(ingredient)
            .then(function () {
                console.log("Added Ingredient " + ingredient.ingredient_name
                + " to Recipe " + recipe.recipe_name);
            });
        })
    }

})
.finally(function(recipe){
    res.redirect('/recipes');
});
});

Any help would be greatly appreciated. I know that I am running into issues because of trying to use promises inside of a loop, I just don't know how else I can accomplish this.

Body:
I was able to fix the problem that I was having. The answers here helped me come up with my solution.
I am posting the solution below in case anyone else runs into a similar issue. I created a variable to store the Promise from Recipe.create(), I used Promise.map to findOrCreate all of the ingredients from the form data. Because findOrCreate returns an array containing Promise and a boolean for if the item was created, I then had to get the actual ingredients out of the results of the Promise.map function. So I used the JavaScript array.map() function to get the first item from the arrays. And finally, use Promise.map again to add each Ingredient to the Recipe

var ingredients = req.body.ingredients,
    recipeName = req.body.recipeName,
    ingredientsQty = {}; // Used to map the ingredient and quantity for the
                         // relationship, because of the Junction Table

var recipe = models.Recipe.create({recipe_name: recipeName});

// Use Promise.map to findOrCreate all ingredients from the form data
Promise.map(ingredients, function(ing){
    ingredientsQty[ing.ingredient_name] = ing.ingredient_quantity;
    return models.Ingredient.findOrCreate({ where: { ingredient_name: ing.ingredient_name}});
})

// Use JavaScript's Array.prototype.map function to return the ingredient
// instance from the array returned by findOrCreate
.then(function(results){
    return results.map(function(result){
        return result[0];
    });
})

// Return the promises for the new Recipe and Ingredients
.then(function(ingredientsInDB){
    return Promise.all([recipe, ingredientsInDB]);
})

// Now I can use Promise.map again to create the relationship between the /
// Recipe and each Ingredient
.spread(function(addedRecipe, ingredientsToAdd){
    recipe = addedRecipe;
    return Promise.map(ingredientsToAdd, function(ingredientToAdd){
        ingredientToAdd.RecipeIngredients = {
            ingredient_quantity: ingredientsQty[ingredientToAdd.ingredient_name]
        };

        return recipe.addIngredient(ingredientToAdd);
    });
})

// And here, everything is finished
.then(function(recipeWithIngredients){
   res.end
});


问:
Why doesn't debugger stop at breakpoint?
I have the problem that the chrome debugger for JS doesn't stop every time I execute one certain function. I tried debugger; and also setting breakpoints where I want the code to stop by putting a blue tag on the gutter next to the line on the left.

any ideas why this happens?

答: I found that code referenced by a  tag with the async property inside of it don't stop at breakpoints in developer mode.</p>

ContentLicense: CC BY-SA 4.0


问:
Issue with Image View and onClickListener
Im new to android programming and I am trying to build an app with imageviews that open up a new activity for each image view clicked with an image view of their own. so far i have made my main activity and put 4 image views on it all below each other with constraints. all works fine in the sense of when i open the app, the image views are laid out how they should be and i can click on imageview1, then 2, then 3, then 4 and then any of them. but if i open the app and try to click on imageview 2 first or imageview 3 for example, or imageview 4 then it doesn't work. I have to start at 1 and then go on to 2 and then 3 and 4 and then finally i can navigate freely. How can I fix this? I have posted my main activity java file below before. Any help would be appreciated. </p>

```<code>package com.ntq.ntqapp;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;

public class MainActivity1 extends AppCompatActivity {
private ImageView ts;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main1);

    ts  = (ImageView)findViewById(R.id.ts1);
    ts.setOnClickListener(new View.OnClickListener(){
        public void onClick(View view){
            Intent myIntent = new Intent(MainActivity1.this, imageView1.class);
            startActivity(myIntent);

     ts = (ImageView)findViewById(R.id.ts2);
     ts.setOnClickListener(new View.OnClickListener(){
         public void onClick(View view) {
             Intent myIntent = new Intent(MainActivity1.this, imageView2.class);
             startActivity(myIntent);

     ts = (ImageView)findViewById(R.id.ts3);
     ts.setOnClickListener(new View.OnClickListener(){
           public void onClick(View view) {
           Intent myIntent = new Intent(MainActivity1.this, imageView3.class);
           startActivity(myIntent);

     ts = (ImageView) findViewById(R.id.ts4);
     ts.setOnClickListener(new View.OnClickListener() {
              public void onClick(View view) {
              Intent myIntent = new Intent(view.getContext(), imageView4.class);
           startActivity(myIntent);

         }

         }
         );
        }}
         );
        }});}});}}
</code>```

答:
You are using the same variable for all the views: private ImageView ts

Use 4 different variables (ts1, ts2...) that will fix your sequence issue !!

Body:
Im new to android programming and I am trying to build an app with imageviews that open up a new activity for each image view clicked with an image view of their own. so far i have made my main activity and put 4 image views on it all below each other with constraints. all works fine in the sense of when i open the app, the image views are laid out how they should be and i can click on imageview1, then 2, then 3, then 4 and then any of them. but if i open the app and try to click on imageview 2 first or imageview 3 for example, or imageview 4 then it doesn't work. I have to start at 1 and then go on to 2 and then 3 and 4 and then finally i can navigate freely. How can I fix this? I have posted my main activity java file below before. Any help would be appreciated.

package com.ntq.ntqapp;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;

public class MainActivity1 extends AppCompatActivity {
private ImageView ts;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main1);

    ts  = (ImageView)findViewById(R.id.ts1);
    ts.setOnClickListener(new View.OnClickListener(){
        public void onClick(View view){
            Intent myIntent = new Intent(MainActivity1.this, imageView1.class);
            startActivity(myIntent);

     ts = (ImageView)findViewById(R.id.ts2);
     ts.setOnClickListener(new View.OnClickListener(){
         public void onClick(View view) {
             Intent myIntent = new Intent(MainActivity1.this, imageView2.class);
             startActivity(myIntent);

     ts = (ImageView)findViewById(R.id.ts3);
     ts.setOnClickListener(new View.OnClickListener(){
           public void onClick(View view) {
           Intent myIntent = new Intent(MainActivity1.this, imageView3.class);
           startActivity(myIntent);

     ts = (ImageView) findViewById(R.id.ts4);
     ts.setOnClickListener(new View.OnClickListener() {
              public void onClick(View view) {
              Intent myIntent = new Intent(view.getContext(), imageView4.class);
           startActivity(myIntent);

         }

         }
         );
        }}
         );
        }});}});}}


问:
What do %% and % in these queries mean?
I have the following 2 Python codes:

```<code>def direct_by_node(self, node, partition_size):
    return '''select req.id, req.profile_id as profile
                  from table1 attr
                  where id % {0} = {1}'''.format(partition_size, node)
</code>```

and then

```<code>def find_by_node(self, node, partition_size):
    return '''select req.id, req.profile_id as profile
                  from table1 attr
                  where id %% {0} = {1}'''.format(partition_size, node)
</code>```

I am wondering what % and %% in the 2 MySQL queries are about?

Edit:

When I try %% in MySQL Workbench, looks like I have a syntax error, looks like %% is invalid.

答:
The first one is a Modulo operation and calculates the remainder of id divided by partition_size then compare it with node.

Look at a simple example here:

```<code>mysql> SELECT 253 % 7;
    -> 1 # because 253 = 36*7 + 1
</code>```

More function_mod examples

As you noticed %% is not a valid operator.

Title: What do %% and % in these queries mean?

Body:
I have the following 2 Python codes:

def direct_by_node(self, node, partition_size):
    return '''select req.id, req.profile_id as profile
                  from table1 attr
                  where id % {0} = {1}'''.format(partition_size, node)

and then

def find_by_node(self, node, partition_size):
    return '''select req.id, req.profile_id as profile
                  from table1 attr
                  where id %% {0} = {1}'''.format(partition_size, node)

I am wondering what % and %% in the 2 MySQL queries are about?

Edit:

When I try %% in MySQL Workbench, looks like I have a syntax error, looks like %% is invalid.

Body:
The first one is a Modulo operation and calculates the remainder of id divided by partition_size then compare it with node.

Look at a simple example here:

mysql> SELECT 253 % 7;
    -> 1 # because 253 = 36*7 + 1

More function_mod examples

As you noticed %% is not a valid operator.


问:
JSON columns sorting with Footable
I am using footable to display a huge table. I am displaying the columns in json:

```<code>"columns": $.get("/masteradmin/full-report-columns/", postdata_columns, 'json'),
</code>```

I want to sort the month columns by default. How I can set a data-sort-initial="descending" variable in the json?

```<code>{
    "name": "month",
    "title": str(_("Month")),
    "type": "date",
    "formatString": "MMMM YYYY"
},
</code>```

Thanks

答:
The examples show how to achieve this: http://fooplugins.github.io/FooTable/docs/components/sorting.html#options</p>

```<code>{
    "name": "month",
    "title": str(_("Month")),
    "type": "date",
    "formatString": "MMMM YYYY",
    "sorted": true,
    "direction": "DESC"
},
</code>```

Title: JSON columns sorting with Footable

Body:
I am using footable to display a huge table. I am displaying the columns in json:

"columns": $.get("/masteradmin/full-report-columns/", postdata_columns, 'json'),

I want to sort the month columns by default. How I can set a data-sort-initial="descending" variable in the json?

{
    "name": "month",
    "title": str(_("Month")),
    "type": "date",
    "formatString": "MMMM YYYY"
},

Thanks

Body:
The examples show how to achieve this: http://fooplugins.github.io/FooTable/docs/components/sorting.html#options

{
    "name": "month",
    "title": str(_("Month")),
    "type": "date",
    "formatString": "MMMM YYYY",
    "sorted": true,
    "direction": "DESC"
},


答:
You are using the same variable name ts for all the views.

Change to ts1, ts2, ts3, ts4.

Also there are some issues with closing parentheses.

You need to close the parentheses for the onClick method, for the inner classes and for the outer method each time.

```<code>ts1 = (ImageView) findViewById(R.id.ts1);
ts.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        Intent myIntent = new Intent(MainActivity1.this, imageView1.class);
        startActivity(myIntent);
    } //you are missing this
}); //and this

// Notice how I change the variable name to ts2 here...
ts2 = (ImageView)findViewById(R.id.ts2);
//rinse and repeat...
</code>```

Title: Issue with Image View and onClickListener

Body:
You are using the same variable name ts for all the views.

Change to ts1, ts2, ts3, ts4.

Also there are some issues with closing parentheses.

You need to close the parentheses for the onClick method, for the inner classes and for the outer method each time.

ts1 = (ImageView) findViewById(R.id.ts1);
ts.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        Intent myIntent = new Intent(MainActivity1.this, imageView1.class);
        startActivity(myIntent);
    } //you are missing this
}); //and this

// Notice how I change the variable name to ts2 here...
ts2 = (ImageView)findViewById(R.id.ts2);
//rinse and repeat...


问:
HTTP 400 vs HTTP 404 for a malformed URI api request
So imagine we have an endpoint called /guest/{guestId}. This endpoint has a GET function where if you provide it a guestId it will return an object with all of the guest information.

The question is what should be returned in each of these scenarios -

guestId = "" leading to /guest/

guestId = "invalidId" leading to /guest/invalidId

The HTTP 1.1 documentation seems to leave room open for either in terms of passing an invalid ID but suggests a 404 when the guestId is blank. For an invalid ID, it's technically hitting the endpoint but just giving it malformed syntax which points towards a 400 but at the same time provides the server with an invalid URI which points to a 404.

What is factually and not opinion-basedly correct?

答:
There's no room for interpretation here. The resource at /guest/invalidId doesn't exist and should return a 404.

The request itself wasn't really 'malformed' in anyway, it just used a uri that was pointing to a non-existent resource. It's malformed, maybe in the perspective of your specific application (it's not a valid id), but it is not from the perspective of the HTTP protocol.

As a general rule this might help as well:

When you want to emit an error to a client, and the client is responsible. You'll want to emit an error in the 400-499 range. If you can't find a good specific error to meet your specific error condition, only then you'll really want to use 400, as in practice it's kind of used as a status code when nothing else really is fitting.


问:
awk command returns inconsistent result
I have a script which performs several validations in a file.
One of the validation is to check if a line exceeds 95 characters (including spaces). If it does, it will return the line number/s where the line exceeds 95 characters. Below is the command used for the validation:

```<code>$(cat $FileName > $tempfile)
totalCharacters=$(awk '{print length($0);}' $tempFile | grep -vn [9][4])
if [[$totalCharacters != "" ]]; then
  totalCharacters=$(awk '{print length($0);}' $tempFile | grep -vn [9][4] | cut -d : -f1 | tr "\n" ",")
  echo "line too long"
  exit 1
fi
</code>```

In the lower environment the code is working as expected. But in production, there are time that the validation returns the error "line too long" but does not return any line number. We just reran the script and it does not return any error.

I would like to know what could be wrong in the command used.
The previous developer who worked on this said that it could be an issue with the use of the awk command, but I am not sure since this is the first time I have encountered using the awk command.

答:
Your script should just be:</p>

```<code>awk '
    length()>95 { printf "%s%d", (c++?",":""), NR }
    END { if (c) {print "line too long"; exit 1} }
' "$FileName"
</code>```

Title: awk command returns inconsistent result

Body:
I have a script which performs several validations in a file.
One of the validation is to check if a line exceeds 95 characters (including spaces). If it does, it will return the line number/s where the line exceeds 95 characters. Below is the command used for the validation:

$(cat $FileName > $tempfile)
totalCharacters=$(awk '{print length($0);}' $tempFile | grep -vn [9][4])
if [[$totalCharacters != "" ]]; then
  totalCharacters=$(awk '{print length($0);}' $tempFile | grep -vn [9][4] | cut -d : -f1 | tr "\n" ",")
  echo "line too long"
  exit 1
fi

In the lower environment the code is working as expected. But in production, there are time that the validation returns the error "line too long" but does not return any line number. We just reran the script and it does not return any error.

I would like to know what could be wrong in the command used.
The previous developer who worked on this said that it could be an issue with the use of the awk command, but I am not sure since this is the first time I have encountered using the awk command.

Body:
Your script should just be:

awk '
    length()>95 { printf "%s%d", (c++?",":""), NR }
    END { if (c) {print "line too long"; exit 1} }
' "$FileName"


Title: Quick format adjustment- adjusting word placement in Javascript

Body:
I've tried to figure this out on my own, but my code is written so intricately that I can't figure out how to change this up.

My code:

var  stocks= [
  ["Beef (80/20) raw","oz",115.4451262,3.293742347,72,4.85,5.65,0,2.142,19,20,0.0001275510204,0.375,0.75,22.15988372,0.3768292943,4  ],
  ["Beef (90/10) raw","oz",115.4451262,3.293742347,50,5.65,2.83,0,1.109,19,18,0.0001275510204,0.375,0.75,22.15988372,0.3768292943,4  ],
  ["Chicken breast","oz",32.39053977,0.3923520408,34,6.38,0.74,0,0.16,13,21,0.01631172356,0.10625,0.2125,3.149953226,0.3765300698,4  ],
  ["Chicken thighs/legs","oz",32.39053977,0.3923520408,125,2.72,12.54,0,3.431,14,30,0.01631172356,0.10625,0.2125,3.149953226,0.3765799405,4  ],
  ["Milk (whole)","fl oz",7.638924987,0.146234933,19,0.96,0.99,1.54,0.569,13,3,3.571428571e-7,0.099609375,0.19921875,1.228661955,0.2415694159,8  ],
  ["Milk (2%)","fl oz",7.638924987,0.06133157758,15,1.06,0.58,1.54,0.363,16,2,3.571428571e-7,0.099609375,0.19921875,1.228661955,0.2417190282,8  ],
  ["Pizza (cheese)","slice",42,0.976332736,285,12.19,10.37,3.83,4.778,640,18,0.00001071428571,2.98828125,5.9765625,36.85985865,0.466697922,4  ],
  ["Ice Cream","cup",32.59312,0.6191784396,274.71344,4.6095984,14.4806576,27.9835216,8.94913952,107.09168,55.87392,0.000003990994286,1.11311325,2.2262265,13.73003196,2.889031735,1  ],
  ["Milk (skim)","fl oz",7.638924987,0.05948052127,10,1.03,0.02,1.54,0.017,13,1,3.571428571e-7,0.099609375,0.19921875,1.228661955,0.2415694159,8  ],
  ["Eggs (large)","each",43.13341461,0.5215603261,78,6.29,5.3,0.2,1.633,62,186,0.001666666667,0.265625,0.53125,3.713549,0.1305756192,1  ],
  ["Lamb","oz",78.125,4.010117347,80,4.69,6.64,0,2.889,17,21,0.03333333333,0.3125,0.625,2.274815967,0.3767295528,4  ],
  ["Cheese (hard)","slice (oz)",37.44571072,1.35234933,105,6.59,8.41,0.14,5.32,159,27,0.000003571428571,0.99609375,1.9921875,12.28661955,0.1303337926,1  ],
  ["Yogurt","oz",5.833333333,0.09395993304,17,0.98,0.92,1.32,0.595,13,4,3.571428571e-7,0.099609375,0.19921875,1.228661955,0.2229453548,6  ],
  ["Greek yogurt, vanilla (nonfat)","fl oz",15,0.08285194565,22,2.45,0.05,1.01,0.038,10,1,8.928571429e-7,0.3984375,0.796875,3.071654888,0.1965527472,6  ],
  ["Chocolate","oz",127.316,0.1863325866,151,2.16,8.39,14.57,5.238,22,7,7.142857143e-8,0.019921875,0.03984375,1.601963425,1.345070603,1.45  ],
  ["Cacao","oz",179.739,0.625,136,1.19,8.51,15.45,5.032,3,0,0,0,0,3.390577585,1.418619303,1.45  ],
  ["Salmon (farmed)","oz",0.498125,0.56925,59,5.79,3.8,0,0.864,17,16,0.004464285714,0.078125,0.15625,0.5593288054,0.3767295528,4  ],
  ["Tuna (canned in oil)","oz",0.498125,0.1197485281,56,8.26,2.33,0,0.435,118,5,0.000270197828,1.0625,2.125,0.5593288054,0.3817664985,4  ],
  ["Mayo","oz",14.41309121,0.1237135815,193,0.27,21.22,0.16,3.318,180,12,0.0004166666667,0.06640625,0.1328125,0.92838725,0.1330741748,0.5  ],
  ["Pulled Pork raw","oz",44.84498316,0.7763814526,53,4.94,3.5,0,1.232,17,18,0.0005208333333,0.21875,0.4375,1.592371177,0.3767295528,4  ],
  ["Butter (salted)","oz",41.58720633,0.5919085938,203,0.24,22.95,0.02,14.537,182,61,0.0000075,2.091796875,4.18359375,25.80190106,0.121322241,1  ],
  ["Soy Burger","oz",21.8,0.048125,50,4.44,1.78,0.3,0.408,161,1,0,0,0,2.314125,0.03342563782,4  ],
  ["Vegan Nuggets (soy)","oz",21.8,0.048125,52,4.88,1.63,0.65,0.325,172,0,0,0,0,2.314125,0.06360340429,4  ],
  ["Soymilk (original)","fl oz",2.319532348,0.02445449777,17,1,0.54,1.21,0.063,16,0,0,0,0,1.168382863,0.1032302684,8  ],
  ["Tofu","oz",25.25,0.09625,23,2.82,1.49,0.2,0.26,1,0,0,0,0,4.62825,0.01698083545,4  ],
  ["Tempeh","oz",12.383064,0.0230998152,54,5.74,3.06,0,0.719,3,0,0,0,0,1.110771114,0.0001496122504,4  ],
  ["Mixed Nuts","oz",18.72285536,0.18425,172,5.53,15.17,1.42,2.271,1,1,0,0,0,1.019662873,0.1202597201,1  ],
  ["Bread","slice",9.735884788,0.1530147137,79,3.09,1.31,1.66,0.202,137,0,0,0,0,0.5625,0.1473592997,2  ],
  ["Lentils","oz",30.3684714,0.07425,33,2.55,0.11,0.51,0.015,1,0,0,0,0,2.287814892,0.04322383072,7.1  ],
  ["Black Beans","oz",30.3684714,0.141625,37,2.31,0.1,0.09,0.025,1,0,0,0,0,1.555714169,0.007668804863,7.1  ],
  ["Tomato Sauce","oz",3.13704,0.09375,11,0.47,0.06,1.37,0.008,57,0,0,0,0,0.4188459746,0.1188197409,8  ],
  ["Pinto Beans","oz",30.3684714,0.141625,40,2.55,0.18,0.09,0.038,0,0,0,0,0,0.9075003086,0.007618934113,7.1  ],
  ["French Fries","oz",2.9337142,0.0417335921,56,0.82,1.91,0.14,0.359,113,0,0,0,0,0.4200133922,0.01748707005,4  ],
  ["Peanut Butter","oz",36,0.2145,167,6.81,14.13,2.97,2.153,138,0,0,0,0,3.675378676,0.2583069893,1  ],
  ["Olive Oil","oz",21.77842536,0.2306145384,250,0,28.3,0,3.908,1,0,0,0,0,1.512500057,0.00004987075014,0.5  ],
  ["Banana","medium",6.440662244,0.1763699536,105,1.29,0.39,14.43,0.132,1,0,0,0,0,0.1768995697,1.221618974,1  ],
  ["Mixed vegetables","oz",2.41150377,0.125,18,0.81,0.04,0,0.009,10,0,0,0,0,3,0.0004987075014,4  ],
  ["Nutritional Yeast","g",0.08506329224,0.00706361088,3.9859577,0.5989518739,0,0,0,0,0,0,0,0,0,0,5  ],
  ["Rice (white)","oz",25.46308329,0.34375,102,1.87,0.16,0,0.045,0,0,0,0,0,0.3995205753,0,2  ],
  ["Potatoes","oz",1.872285536,0.03575,16,0.73,0.03,0.2,0.007,3,0,0,0,0,0.06927480776,0.01708057695,5.3  ],
  ["Vegetable Oil","oz",17.70433203,0.125,205,0,23.8,0,19.937,0,0,0,0,0,5.300817694,0,0.5  ],
  ["Wheat (flour)","cup",40.44136758,0.1235081329,408,13.56,1.88,0.36,0.276,4,0,0,0,0,1.598082301,0.03067521945,0.25  ],
  ["Margarine","oz",9.915624199,0.06125,102,0.28,11.32,0,2.048,222,0,0,0,0,5.300817694,0.01107130653,1  ],
  ["Corn Syrup","fl oz",11.15931776,0.01728062914,109,0,0,29.31,0,1,0,0,0,0,0.4854914297,2.481282747,1  ],
  ["Sugar","oz",11.23371322,0.01503093504,110,0,0,28.3,0,0,0,0,0,0,0.4340729937,2.395731504,1  ],
  ["Corn (grain)","oz",6.74022793,0.0104375,103,2.67,1.34,0.18,0.189,10,0,0,0,0,0.4549631935,0.01573657573,1  ],
  ["Soda","fl oz",10.64647779,0.02494335117,13,0,0.08,3.05,0,1,0,0,0,0,0.1939638153,0.2582470824,12  ]
]
function Stock (data) {
  return {
    name: data[0],
    servingUnit: data[1],
    water: [data[2], ''],
    carbon: [data[3], ''],
    calories: [data[4], ''],
    protein: [data[5], 'g'],
    fat: [data[6], 'g'],
    saturatedFat: [data[8], 'g'],
    sugar: [data[7], 'g'],
    sodium: [data[9], 'mg'],
    cholesterol: [data[10], 'mg'],
    lives: [data[11], ''],
    feed: [data[12], ''],
    meals: [data[13], ''],
    land : [data[14], ''],
    healthcare : [data[15], ''],
    unitsPerServing: data[data.length - 1]
  }
}

stocks = stocks.map(Stock)

var $selects = $('.selectStock')
var $quantity = $('#numberOfStocks')
var $comparisonResult = $('.comparison .result')

$selects.each(function() {
  $(this).append(stocks.map(function(stock, i) {
    return new Option(stock.name, i)
  }))
})

function format(data, multiplier, digits,a) {
  data = data.slice()
  data[0] = (+(data[0] * multiplier).toFixed(digits)).toLocaleString();
    console.log(data);
  if(a=="bad" && data[2]==" + "){
  data[0]=""+data[0]+""
  }
  if(a=="bad" && data[2]==" - "){
  data[0]=""+data[0]+""
  }
  else if (a=="good" && data[2]==" - "){
  data[0]=""+data[0]+""
  }
  else if (a=="good" && data[2]==" + "){
  data[0]=""+data[0]+""
  }
  if(a=="bad" && data[2]=="use"){
  data[0]=""+data[0]+""
  }
  if(a=="bad" && data[2]=="save"){
  data[0]=""+data[0]+""
  }
  else if (a=="good" && data[2]=="save"){
  data[0]=""+data[0]+""
  }
  else if (a=="good" && data[2]=="use"){
  data[0]=""+data[0]+""
  }
  return data.join(' ')
}

function format2(data, multiplier, digits,a) {
  data = data.slice()
  data[0] = (+(data[0] * multiplier).toFixed(digits)).toLocaleString();
    console.log(data);
  if(a=="use" && data[2]==" + "){
  data[0]=""+data[0]+""
  }
  if(a=="use" && data[2]==" - "){
  data[0]=""+data[0]+""
  }
  else if (a=="emit" && data[2]=="use"){
  data[0]=""+data[0]+""
  }
  else if (a=="emit" && data[2]=="save"){
  data[0]=""+data[0]+""
  }
  if(a=="consumegood" && data[2]=="more"){
  data[0]=""+data[0]+""
  }
  if(a=="consumegood" && data[2]=="less"){
  data[0]=""+data[0]+""
  }
  return data.join(' ')
}
function stockFacts(stock, quantity) {
  return [
    format(stock.water, quantity, 2,"bad","use") + ' gallons of water
' +
    format(stock.carbon, quantity, 2,"bad","emit") + ' pounds of carbon dioxide and methane equivalents
' +
    format(stock.calories, quantity, 2,"bad","consume") + ' calories
' +
    format(stock.protein, quantity, 2,"good","consumegood") + ' of protein
' +
    format(stock.fat, quantity, 3,"bad","consume") + ' of fat
' +
    format(stock.saturatedFat, quantity, 2,"bad","consume") + ' of saturated fat
' +
    format(stock.sugar, quantity, 2,"bad","consume") + ' of sugar
' +
    format(stock.sodium, quantity, 2,"bad","consume") + ' of sodium
' +
    format(stock.cholesterol, quantity, 2,"bad","consume") + ' of cholesterol
' +
    format(stock.lives, quantity, 5,"bad","save") + ' animal lives
' +
    format(stock.feed, quantity, 2,"bad","require") + ' pounds of feed
' +
    format(stock.meals, quantity, 2,"bad","preserve") + ' meals made from feed
' +
    format(stock.land, quantity, 2,"bad","require") + ' square feet of land needed
' +
    "$"+format(stock.healthcare, quantity, 2,"bad","save") + ' in projected healthcare costs
'
  ]
}

function stockFactsEnv(stock, quantity) {
  return [
    format(stock.water, quantity, 2,"bad","use") + ' gallons of water
' +
    format(stock.carbon, quantity, 2,"bad","emit") + ' pounds of carbon dioxide and methane equivalents
' +
    format(stock.land, quantity, 2,"bad","require") + ' square feet of land needed
'
  ]
}

function stockFactsHealth(stock, quantity) {
  return [
    format(stock.calories, quantity, 2,"bad","consume") + ' calories
' +
    format(stock.protein, quantity, 2,"good","consumegood") + ' of protein
' +
    format(stock.fat, quantity, 3,"bad","consume") + ' of fat
' +
    format(stock.saturatedFat, quantity, 2,"bad","consume") + ' of saturated fat
' +
    format(stock.sugar, quantity, 2,"bad","consume") + ' of sugar
' +
    format(stock.sodium, quantity, 2,"bad","consume") + ' of sodium
' +
    format(stock.cholesterol, quantity, 2,"bad","consume") + ' of cholesterol
' +
    "$"+format(stock.healthcare, quantity, 2,"bad","save") + ' in projected healthcare costs
'
  ]
}

function stockFactsSocial(stock, quantity) {
  return [
    format(stock.lives, quantity, 5,"bad","save") + ' animal lives
' +
    format(stock.feed, quantity, 2,"bad","require") + ' pounds of feed
' +
    format(stock.meals, quantity, 2,"bad","preserve") + ' meals made from feed
'
  ]
}

function stockFacts2(stock, quantity) {
  return [
    format(stock.water, (quantity/50), 2,"bad","use") + ' bathtubs worth of water used
' +
    format(stock.carbon, (quantity*23.6/(20)), 2,"bad","emit") + ' miles worth of carbon dioxide driven in a car
' +
    format(stock.calories, quantity, 2,"bad","consume") + ' calories
' +
    format(stock.protein, quantity, 2,"good","consumegood") + ' of protein
' +
    format(stock.fat, quantity, 3,"bad","consume") + ' of fat
' +
    format(stock.saturatedFat, quantity, 2,"bad","consume") + ' of saturated fat
' +
   format(stock.sugar, quantity, 2,"bad","consume") + ' of sugar
' +
   format(stock.sodium, quantity, 2,"bad","consume") + ' of sodium
' +
   format(stock.cholesterol, quantity, 2,"bad","consume") + ' of cholesterol
' +
   format(stock.lives, quantity, 5,"bad","save") + ' animal lives needed
' +
   format(stock.feed, quantity, 2,"bad","require") + ' pounds of feed required
' +
    "Be able to feed " + format(stock.meals, (quantity/365/3), 2,"bad","preserve") + ' people for an entire year
' +
   format(stock.land, (quantity/43560), 2,"bad","require") + ' acres of land needed
' +
  "$"+format(stock.healthcare, quantity, 2,"bad","save") + 'in projected healthcare costs
'
  ]
}

function stockFacts3(stock, quantity) {
  return [
    format(stock.water, (quantity/660430), 2,"bad","use") + ' Olympic swimming pools worth of water
' +
    format(stock.carbon, (quantity/12000), 2,"bad","emit") + ' cars worth of carbon dioxide
' +
   format(stock.lives, quantity, 5,"bad","save") + ' animal lives
' +
    "Be able to feed " + format(stock.meals, (quantity/3/365), 2,"bad","preserve") + ' people for an entire year
' +
    format(stock.land, (quantity/43560), 2,"bad","require") + ' acres of land required
' +
   "$"+format(stock.healthcare, quantity, 2,"bad","save") + ' in projected healthcare costs'
  ]
}

$selects.add($quantity).on('input', updateAmount)

function getStock (select) {
  return stocks[+select.value]
}

function updateAmount() {
  var quantity = +$quantity.val()

  $selects.each(function() {
    var $result = $(this).nextAll('.result').empty()
    var $amount = $(this).prev().find('.servingUnit').empty()
    var stock = getStock(this)
    if (!stock) return
    var amount = quantity * stock.unitsPerServing

    $amount.text(' (' + amount + ' ' + stock.servingUnit + ') of:')

    $result.html(stockFacts(stock, amount))
  })

  var selected = [].map.call($selects, getStock)
  $comparisonResult.empty()
  if (!selected[0] || !selected[1]) return
  var difference = {};
  var diff = {}
  Object.keys(selected[0]).forEach(function (k) {
    if (/^(name|servingUnit|unitsPerServing)$/.test(k)) return
    var first = selected[0][k].slice()
    var second = selected[1][k].slice()
    first[0] *= selected[0].unitsPerServing
    second[0] *= selected[1].unitsPerServing
    difference[k] = [Math.abs(first[0] - second[0]), first[1], first[0] > second[0] ? 'save' : 'use'];
    diff[k] = [Math.abs(first[0] - second[0]), first[1], first[0] > second[0] ? ' + ' : ' - ']
  })

  $comparisonResult.html(stockFacts(diff, quantity));
 $('#env_result').html(stockFactsEnv(diff, quantity));
  $('#health_result').html(stockFactsHealth(diff, quantity));
  $('#soc_result').html(stockFactsSocial(diff, quantity));
 $('#year_result').html(stockFacts2(diff, quantity*365));
  $('#US_result').html(stockFacts3(diff,quantity*323148587));
}

$selects.add($quantity).on('input', updateAmount)

function getStock (select) {
  return stocks[+select.value]
}

.main-container{

  display: flex;
  flex-wrap: wrap;
}

*{
    padding : 0;
      margin : 0;
}
body{
  height : 100vh;
  background-color: #F8F8FF;
}

.topnav {
  height: 50px;
  width: 100%;
  color: white;
  background-color: #173;
    overflow: hidden;
  text-align: center;

}

/* Style the links inside the navigation bar */
.topnav a {
    float: left;
    display: block;
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 17px;

}

/* Change the color of links on hover */
.topnav a:hover {
    background-color: #ddd;
    color: black;
}

/* Add a color to the active/current link */
.topnav a.active {
    background-color: #4CAF50;
    color: white;
}

.box-1{
  width : 25%;
  margin-left: 5%;
  display : block;
  text-align : center;
  font-size : 1.5em;

}

.box{
  width : 22%;
  display : block;
  text-align : center;
  font-size : 1.5em;
}

.box-2{
  width : 48%;
  margin-top: 1%;
  display : block;
    text-align : center;
  font-size : 1.5em;
}

@media screen and (max-width: 480px) {
.box{
display : block;
width : auto;

}

.box-2{
display : block;
width : auto;

}
}

.color-red{
color:red;
background:transparent}
.color-green{
color:green;
background:transparent}

    <link rel="stylesheet" href="style.css">

    <link rel="stylesheet" type="text/css" href="semantic/dist/semantic.min.css">

      Ingredient Calculator
  Meal Calculator
  About
  Contact
  Sources

    Servings:

    <input type="number" id="numberOfStocks" value="1" min="0" />

The impact of eating

        <select class="ui fluid search dropdown selectStock">
          <option value="-1">Pick a food!</option>
        </select>

          vs.

        <select class="selectStock">
          <option value="-1">Pick a food!</option>
        </select>

 Environmental Impact:

 Health Impact:

<img src="data:image/svg+xml;utf8;base64,[encoded data, 4272 characters]" /> Social Impact:

        Impact of making this switch everyday for a year:

Impact of everyone in the US making this switch just once:

Basically, I just need to change the code so that the "+" or "-" after the number actually comes before- so it's "-100 gallons of water" instead of "100 - gallons of water".

Any help/guidance would be appreciated. Thanks!

Body:
EDIT

I managed to place the $ sign after the + or - sign.

So instead of:

"$"+format(stock.healthcare, quantity, 2,"bad","save") + ' in projected healthcare costs<br>'

It now is ($ is sent to the function):

format(stock.healthcare, quantity, 2,"bad","save","$")

And in the function, it places the $ at the right place within the returned string.

var temp=[];
if(unit=="$"){
  temp = [data[2],"$",data[0],data[1]];
}else{
  temp = [data[2],data[0],data[1]];
}
return temp.join(' ');

See CodePen version #2.

FIRST answer:

I just changed the array order before the returned join(' ') in both format() and format2()

var temp = [data[2],data[0],data[1]];
return temp.join(' ');

Instead of:

return data.join(' ')

See in CodePen Too.

var  stocks= [
  ["Beef (80/20) raw","oz",115.4451262,3.293742347,72,4.85,5.65,0,2.142,19,20,0.0001275510204,0.375,0.75,22.15988372,0.3768292943,4  ],
  ["Beef (90/10) raw","oz",115.4451262,3.293742347,50,5.65,2.83,0,1.109,19,18,0.0001275510204,0.375,0.75,22.15988372,0.3768292943,4  ],
  ["Chicken breast","oz",32.39053977,0.3923520408,34,6.38,0.74,0,0.16,13,21,0.01631172356,0.10625,0.2125,3.149953226,0.3765300698,4  ],
  ["Chicken thighs/legs","oz",32.39053977,0.3923520408,125,2.72,12.54,0,3.431,14,30,0.01631172356,0.10625,0.2125,3.149953226,0.3765799405,4  ],
  ["Milk (whole)","fl oz",7.638924987,0.146234933,19,0.96,0.99,1.54,0.569,13,3,3.571428571e-7,0.099609375,0.19921875,1.228661955,0.2415694159,8  ],
  ["Milk (2%)","fl oz",7.638924987,0.06133157758,15,1.06,0.58,1.54,0.363,16,2,3.571428571e-7,0.099609375,0.19921875,1.228661955,0.2417190282,8  ],
  ["Pizza (cheese)","slice",42,0.976332736,285,12.19,10.37,3.83,4.778,640,18,0.00001071428571,2.98828125,5.9765625,36.85985865,0.466697922,4  ],
  ["Ice Cream","cup",32.59312,0.6191784396,274.71344,4.6095984,14.4806576,27.9835216,8.94913952,107.09168,55.87392,0.000003990994286,1.11311325,2.2262265,13.73003196,2.889031735,1  ],
  ["Milk (skim)","fl oz",7.638924987,0.05948052127,10,1.03,0.02,1.54,0.017,13,1,3.571428571e-7,0.099609375,0.19921875,1.228661955,0.2415694159,8  ],
  ["Eggs (large)","each",43.13341461,0.5215603261,78,6.29,5.3,0.2,1.633,62,186,0.001666666667,0.265625,0.53125,3.713549,0.1305756192,1  ],
  ["Lamb","oz",78.125,4.010117347,80,4.69,6.64,0,2.889,17,21,0.03333333333,0.3125,0.625,2.274815967,0.3767295528,4  ],
  ["Cheese (hard)","slice (oz)",37.44571072,1.35234933,105,6.59,8.41,0.14,5.32,159,27,0.000003571428571,0.99609375,1.9921875,12.28661955,0.1303337926,1  ],
  ["Yogurt","oz",5.833333333,0.09395993304,17,0.98,0.92,1.32,0.595,13,4,3.571428571e-7,0.099609375,0.19921875,1.228661955,0.2229453548,6  ],
  ["Greek yogurt, vanilla (nonfat)","fl oz",15,0.08285194565,22,2.45,0.05,1.01,0.038,10,1,8.928571429e-7,0.3984375,0.796875,3.071654888,0.1965527472,6  ],
  ["Chocolate","oz",127.316,0.1863325866,151,2.16,8.39,14.57,5.238,22,7,7.142857143e-8,0.019921875,0.03984375,1.601963425,1.345070603,1.45  ],
  ["Cacao","oz",179.739,0.625,136,1.19,8.51,15.45,5.032,3,0,0,0,0,3.390577585,1.418619303,1.45  ],
  ["Salmon (farmed)","oz",0.498125,0.56925,59,5.79,3.8,0,0.864,17,16,0.004464285714,0.078125,0.15625,0.5593288054,0.3767295528,4  ],
  ["Tuna (canned in oil)","oz",0.498125,0.1197485281,56,8.26,2.33,0,0.435,118,5,0.000270197828,1.0625,2.125,0.5593288054,0.3817664985,4  ],
  ["Mayo","oz",14.41309121,0.1237135815,193,0.27,21.22,0.16,3.318,180,12,0.0004166666667,0.06640625,0.1328125,0.92838725,0.1330741748,0.5  ],
  ["Pulled Pork raw","oz",44.84498316,0.7763814526,53,4.94,3.5,0,1.232,17,18,0.0005208333333,0.21875,0.4375,1.592371177,0.3767295528,4  ],
  ["Butter (salted)","oz",41.58720633,0.5919085938,203,0.24,22.95,0.02,14.537,182,61,0.0000075,2.091796875,4.18359375,25.80190106,0.121322241,1  ],
  ["Soy Burger","oz",21.8,0.048125,50,4.44,1.78,0.3,0.408,161,1,0,0,0,2.314125,0.03342563782,4  ],
  ["Vegan Nuggets (soy)","oz",21.8,0.048125,52,4.88,1.63,0.65,0.325,172,0,0,0,0,2.314125,0.06360340429,4  ],
  ["Soymilk (original)","fl oz",2.319532348,0.02445449777,17,1,0.54,1.21,0.063,16,0,0,0,0,1.168382863,0.1032302684,8  ],
  ["Tofu","oz",25.25,0.09625,23,2.82,1.49,0.2,0.26,1,0,0,0,0,4.62825,0.01698083545,4  ],
  ["Tempeh","oz",12.383064,0.0230998152,54,5.74,3.06,0,0.719,3,0,0,0,0,1.110771114,0.0001496122504,4  ],
  ["Mixed Nuts","oz",18.72285536,0.18425,172,5.53,15.17,1.42,2.271,1,1,0,0,0,1.019662873,0.1202597201,1  ],
  ["Bread","slice",9.735884788,0.1530147137,79,3.09,1.31,1.66,0.202,137,0,0,0,0,0.5625,0.1473592997,2  ],
  ["Lentils","oz",30.3684714,0.07425,33,2.55,0.11,0.51,0.015,1,0,0,0,0,2.287814892,0.04322383072,7.1  ],
  ["Black Beans","oz",30.3684714,0.141625,37,2.31,0.1,0.09,0.025,1,0,0,0,0,1.555714169,0.007668804863,7.1  ],
  ["Tomato Sauce","oz",3.13704,0.09375,11,0.47,0.06,1.37,0.008,57,0,0,0,0,0.4188459746,0.1188197409,8  ],
  ["Pinto Beans","oz",30.3684714,0.141625,40,2.55,0.18,0.09,0.038,0,0,0,0,0,0.9075003086,0.007618934113,7.1  ],
  ["French Fries","oz",2.9337142,0.0417335921,56,0.82,1.91,0.14,0.359,113,0,0,0,0,0.4200133922,0.01748707005,4  ],
  ["Peanut Butter","oz",36,0.2145,167,6.81,14.13,2.97,2.153,138,0,0,0,0,3.675378676,0.2583069893,1  ],
  ["Olive Oil","oz",21.77842536,0.2306145384,250,0,28.3,0,3.908,1,0,0,0,0,1.512500057,0.00004987075014,0.5  ],
  ["Banana","medium",6.440662244,0.1763699536,105,1.29,0.39,14.43,0.132,1,0,0,0,0,0.1768995697,1.221618974,1  ],
  ["Mixed vegetables","oz",2.41150377,0.125,18,0.81,0.04,0,0.009,10,0,0,0,0,3,0.0004987075014,4  ],
  ["Nutritional Yeast","g",0.08506329224,0.00706361088,3.9859577,0.5989518739,0,0,0,0,0,0,0,0,0,0,5  ],
  ["Rice (white)","oz",25.46308329,0.34375,102,1.87,0.16,0,0.045,0,0,0,0,0,0.3995205753,0,2  ],
  ["Potatoes","oz",1.872285536,0.03575,16,0.73,0.03,0.2,0.007,3,0,0,0,0,0.06927480776,0.01708057695,5.3  ],
  ["Vegetable Oil","oz",17.70433203,0.125,205,0,23.8,0,19.937,0,0,0,0,0,5.300817694,0,0.5  ],
  ["Wheat (flour)","cup",40.44136758,0.1235081329,408,13.56,1.88,0.36,0.276,4,0,0,0,0,1.598082301,0.03067521945,0.25  ],
  ["Margarine","oz",9.915624199,0.06125,102,0.28,11.32,0,2.048,222,0,0,0,0,5.300817694,0.01107130653,1  ],
  ["Corn Syrup","fl oz",11.15931776,0.01728062914,109,0,0,29.31,0,1,0,0,0,0,0.4854914297,2.481282747,1  ],
  ["Sugar","oz",11.23371322,0.01503093504,110,0,0,28.3,0,0,0,0,0,0,0.4340729937,2.395731504,1  ],
  ["Corn (grain)","oz",6.74022793,0.0104375,103,2.67,1.34,0.18,0.189,10,0,0,0,0,0.4549631935,0.01573657573,1  ],
  ["Soda","fl oz",10.64647779,0.02494335117,13,0,0.08,3.05,0,1,0,0,0,0,0.1939638153,0.2582470824,12  ]
]
function Stock (data) {
  return {
    name: data[0],
    servingUnit: data[1],
    water: [data[2], ''],
    carbon: [data[3], ''],
    calories: [data[4], ''],
    protein: [data[5], 'g'],
    fat: [data[6], 'g'],
    saturatedFat: [data[8], 'g'],
    sugar: [data[7], 'g'],
    sodium: [data[9], 'mg'],
    cholesterol: [data[10], 'mg'],
    lives: [data[11], ''],
    feed: [data[12], ''],
    meals: [data[13], ''],
    land : [data[14], ''],
    healthcare : [data[15], ''],
    unitsPerServing: data[data.length - 1]
  }
}

stocks = stocks.map(Stock)

var $selects = $('.selectStock')
var $quantity = $('#numberOfStocks')
var $comparisonResult = $('.comparison .result')

$selects.each(function() {
  $(this).append(stocks.map(function(stock, i) {
    return new Option(stock.name, i)
  }))
})

function format(data, multiplier, digits,a) {
  data = data.slice()
  data[0] = (+(data[0] * multiplier).toFixed(digits)).toLocaleString();
    console.log(data);
  if(a=="bad" && data[2]==" + "){
  data[0]="<span class='color-red'>"+data[0]+"</span>"
  }
  if(a=="bad" && data[2]==" - "){
  data[0]="<span class='color-green'>"+data[0]+"</span>"
  }
  else if (a=="good" && data[2]==" - "){
  data[0]="<span class='color-red'>"+data[0]+"</span>"
  }
  else if (a=="good" && data[2]==" + "){
  data[0]="<span class='color-green'>"+data[0]+"</span>"
  }
  if(a=="bad" && data[2]=="use"){
  data[0]="<span class='color-red'>"+data[0]+"</span>"
  }
  if(a=="bad" && data[2]=="save"){
  data[0]="<span class='color-green'>"+data[0]+"</span>"
  }
  else if (a=="good" && data[2]=="save"){
  data[0]="<span class='color-red'>"+data[0]+"</span>"
  }
  else if (a=="good" && data[2]=="use"){
  data[0]="<span class='color-green'>"+data[0]+"</span>"
  }
  var temp = [data[2],data[0],data[1]];
  return temp.join(' ')
}

function format2(data, multiplier, digits,a) {
  data = data.slice()
  data[0] = (+(data[0] * multiplier).toFixed(digits)).toLocaleString();
    console.log(data);
  if(a=="use" && data[2]==" + "){
  data[0]="<span class='color-red'>"+data[0]+"</span>"
  }
  if(a=="use" && data[2]==" - "){
  data[0]="<span class='color-green'>"+data[0]+"</span>"
  }
  else if (a=="emit" && data[2]=="use"){
  data[0]="<span class='color-green'>"+data[0]+"</span>"
  }
  else if (a=="emit" && data[2]=="save"){
  data[0]="<span class='color-red'>"+data[0]+"</span>"
  }
  if(a=="consumegood" && data[2]=="more"){
  data[0]="<span class='color-green'>"+data[0]+"</span>"
  }
  if(a=="consumegood" && data[2]=="less"){
  data[0]="<span class='color-red'>"+data[0]+"</span>"
  }
  var temp = [data[2],data[0],data[1]];
  return temp.join(' ');
}
function stockFacts(stock, quantity) {
  return [
    format(stock.water, quantity, 2,"bad","use") + ' gallons of water<br>' +
    format(stock.carbon, quantity, 2,"bad","emit") + ' pounds of carbon dioxide and methane equivalents <br>' +
    format(stock.calories, quantity, 2,"bad","consume") + ' calories<br>' +
    format(stock.protein, quantity, 2,"good","consumegood") + ' of protein<br>' +
    format(stock.fat, quantity, 3,"bad","consume") + ' of fat<br>' +
    format(stock.saturatedFat, quantity, 2,"bad","consume") + ' of saturated fat<br>' +
    format(stock.sugar, quantity, 2,"bad","consume") + ' of sugar<br>' +
    format(stock.sodium, quantity, 2,"bad","consume") + ' of sodium<br>' +
    format(stock.cholesterol, quantity, 2,"bad","consume") + ' of cholesterol<br>' +
    format(stock.lives, quantity, 5,"bad","save") + ' animal lives<br>' +
    format(stock.feed, quantity, 2,"bad","require") + ' pounds of feed<br>' +
    format(stock.meals, quantity, 2,"bad","preserve") + ' meals made from feed<br>' +
    format(stock.land, quantity, 2,"bad","require") + ' square feet of land needed<br>' +
    "$"+format(stock.healthcare, quantity, 2,"bad","save") + ' in projected healthcare costs<br>'
  ]
}

function stockFactsEnv(stock, quantity) {
  return [
    format(stock.water, quantity, 2,"bad","use") + ' gallons of water<br>' +
    format(stock.carbon, quantity, 2,"bad","emit") + ' pounds of carbon dioxide and methane equivalents <br>' +
    format(stock.land, quantity, 2,"bad","require") + ' square feet of land needed<br>'
  ]
}

function stockFactsHealth(stock, quantity) {
  return [
    format(stock.calories, quantity, 2,"bad","consume") + ' calories<br>' +
    format(stock.protein, quantity, 2,"good","consumegood") + ' of protein<br>' +
    format(stock.fat, quantity, 3,"bad","consume") + ' of fat<br>' +
    format(stock.saturatedFat, quantity, 2,"bad","consume") + ' of saturated fat<br>' +
    format(stock.sugar, quantity, 2,"bad","consume") + ' of sugar<br>' +
    format(stock.sodium, quantity, 2,"bad","consume") + ' of sodium<br>' +
    format(stock.cholesterol, quantity, 2,"bad","consume") + ' of cholesterol<br>' +
    "$"+format(stock.healthcare, quantity, 2,"bad","save") + ' in projected healthcare costs<br>'
  ]
}

function stockFactsSocial(stock, quantity) {
  return [
    format(stock.lives, quantity, 5,"bad","save") + ' animal lives<br>' +
    format(stock.feed, quantity, 2,"bad","require") + ' pounds of feed<br>' +
    format(stock.meals, quantity, 2,"bad","preserve") + ' meals made from feed<br>'
  ]
}

function stockFacts2(stock, quantity) {
  return [
    format(stock.water, (quantity/50), 2,"bad","use") + ' bathtubs worth of water used<br>' +
    format(stock.carbon, (quantity*23.6/(20)), 2,"bad","emit") + ' miles worth of carbon dioxide driven in a car<br>' +
    format(stock.calories, quantity, 2,"bad","consume") + ' calories<br>' +
    format(stock.protein, quantity, 2,"good","consumegood") + ' of protein<br>' +
    format(stock.fat, quantity, 3,"bad","consume") + ' of fat<br>' +
    format(stock.saturatedFat, quantity, 2,"bad","consume") + ' of saturated fat<br>' +
   format(stock.sugar, quantity, 2,"bad","consume") + ' of sugar<br>' +
   format(stock.sodium, quantity, 2,"bad","consume") + ' of sodium<br>' +
   format(stock.cholesterol, quantity, 2,"bad","consume") + ' of cholesterol<br>' +
   format(stock.lives, quantity, 5,"bad","save") + ' animal lives needed <br>' +
   format(stock.feed, quantity, 2,"bad","require") + ' pounds of feed required<br>' +
    "Be able to feed " + format(stock.meals, (quantity/365/3), 2,"bad","preserve") + ' people for an entire year<br>' +
   format(stock.land, (quantity/43560), 2,"bad","require") + ' acres of land needed<br>' +
  "$"+format(stock.healthcare, quantity, 2,"bad","save") + 'in projected healthcare costs<br>'
  ]
}

function stockFacts3(stock, quantity) {
  return [
    format(stock.water, (quantity/660430), 2,"bad","use") + ' Olympic swimming pools worth of water<br>' +
    format(stock.carbon, (quantity/12000), 2,"bad","emit") + ' cars worth of carbon dioxide<br>' +
   format(stock.lives, quantity, 5,"bad","save") + ' animal lives<br>' +
    "Be able to feed " + format(stock.meals, (quantity/3/365), 2,"bad","preserve") + ' people for an entire year<br>' +
    format(stock.land, (quantity/43560), 2,"bad","require") + ' acres of land required<br>' +
   "$"+format(stock.healthcare, quantity, 2,"bad","save") + ' in projected healthcare costs'
  ]
}

$selects.add($quantity).on('input', updateAmount)

function getStock (select) {
  return stocks[+select.value]
}

function updateAmount() {
  var quantity = +$quantity.val()

  $selects.each(function() {
    var $result = $(this).nextAll('.result').empty()
    var $amount = $(this).prev().find('.servingUnit').empty()
    var stock = getStock(this)
    if (!stock) return
    var amount = quantity * stock.unitsPerServing

    $amount.text(' (' + amount + ' ' + stock.servingUnit + ') of:')

    $result.html(stockFacts(stock, amount))
  })

  var selected = [].map.call($selects, getStock)
  $comparisonResult.empty()
  if (!selected[0] || !selected[1]) return
  var difference = {};
  var diff = {}
  Object.keys(selected[0]).forEach(function (k) {
    if (/^(name|servingUnit|unitsPerServing)$/.test(k)) return
    var first = selected[0][k].slice()
    var second = selected[1][k].slice()
    first[0] *= selected[0].unitsPerServing
    second[0] *= selected[1].unitsPerServing
    difference[k] = [Math.abs(first[0] - second[0]), first[1], first[0] > second[0] ? 'save' : 'use'];
    diff[k] = [Math.abs(first[0] - second[0]), first[1], first[0] > second[0] ? ' + ' : ' - ']
  })

  $comparisonResult.html(stockFacts(diff, quantity));
 $('#env_result').html(stockFactsEnv(diff, quantity));
  $('#health_result').html(stockFactsHealth(diff, quantity));
  $('#soc_result').html(stockFactsSocial(diff, quantity));
 $('#year_result').html(stockFacts2(diff, quantity*365));
  $('#US_result').html(stockFacts3(diff,quantity*323148587));
}

$selects.add($quantity).on('input', updateAmount)

function getStock (select) {
  return stocks[+select.value]
}

.main-container{

  display: flex;
  flex-wrap: wrap;
}

*{
  padding : 0;
  margin : 0;
}
body{
  height : 100vh;
  background-color: #F8F8FF;
}

.topnav {
  height: 50px;
  width: 100%;
  color: white;
  background-color: #173;
  overflow: hidden;
  text-align: center;

}

/* Style the links inside the navigation bar */
.topnav a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;

}

/* Change the color of links on hover */
.topnav a:hover {
  background-color: #ddd;
  color: black;
}

/* Add a color to the active/current link */
.topnav a.active {
  background-color: #4CAF50;
  color: white;
}

.box-1{
  width : 25%;
  margin-left: 5%;
  display : block;
  text-align : center;
  font-size : 1.5em;

}

.box{
  width : 22%;
  display : block;
  text-align : center;
  font-size : 1.5em;
}

.box-2{
  width : 48%;
  margin-top: 1%;
  display : block;
  text-align : center;
  font-size : 1.5em;
}

@media screen and (max-width: 480px) {
  .box{
    display : block;
    width : auto;

  }

  .box-2{
    display : block;
    width : auto;

  }
}

.color-red{
  color:red;
  background:transparent}
.color-green{
  color:green;
  background:transparent}

#share-buttons img {
  width: 35px;
  padding: 5px;
  border: 0;
  box-shadow: 0;
  display: inline;
  background: transparent;
}

/* Hide AddToAny vertical share bar when screen is less than 980 pixels wide */
@media screen and (max-width: 980px) {
  .a2a_floating_style.a2a_vertical_style { display: none; }
}

<head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
    <link rel="stylesheet" type="text/css" href="semantic/dist/semantic.min.css">
<script
  src="https://code.jquery.com/jquery-3.1.1.min.js"
  integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
  crossorigin="anonymous"></script>
<script src="semantic/dist/semantic.min.js"></script>
  </head>

  <body>
    <div class="topnav" id="myTopnav">
      <a href="#ingredient">Ingredient Calculator</a>
  <a href="#meal">Meal Calculator</a>
  <a href="#about">About</a>
  <a href="#contact">Contact</a>
  <a href="#sources">Sources</a></div>
  <div class="main-container">
      <div class="box-1">
      <label>
    Servings:
        <br>
    <input type="number" id="numberOfStocks" value="1" min="0" />
  </label>
        <br>
        <h3>The impact of eating<span class="servingUnit"></span></h3>
        <select class="ui fluid search dropdown selectStock">
          <option value="-1">Pick a food!</option>
        </select>
        <h3>
          <br>
          vs.
        <span class="servingUnit"></span></h3>
        <select class="selectStock">
          <option value="-1">Pick a food!</option>
        </select>
        <br>
        <h2></h2>
      </div>
      <div class="box"><i class="fa fa-car" style="color:#A9A9A9"></i> Environmental Impact:</h2><div id="env_result"></div></div>
      <div class="box"><i class="fa fa-heartbeat" style="color:#FF69B4"></i> Health Impact:</h2><div id="health_result"></div></div>
      <div class="box"><img src="data:image/svg+xml;utf8;base64,[encoded data, 4272 characters]" /> Social Impact:
      <div id="soc_result"></div></div>
    <br>
      <div class="box-2"><h3>
        Impact of making this switch everyday for a year:</h3>
<div id="year_result">
        </div></div>
<div class="box-2"> <h3>Impact of everyone in the US making this switch just <b>once</b>:</h3>
<div id="US_result">
</div></div>
</div></div>
  </body>

<div class="a2a_kit a2a_kit_size_32 a2a_floating_style a2a_vertical_style" style="left:0px; top:150px;">
    <a class="a2a_button_facebook"></a>
    <a class="a2a_button_twitter"></a>
    <a class="a2a_button_google_plus"></a>
    <a class="a2a_button_pinterest"></a>
</div>

<script async src="https://static.addtoany.com/menu/page.js"></script>