问:
React Component not Rendering New Data from Redux Store
This issue comes into play because my high-level components are called before I obtain my initial state via a websocket in the form of a redux store. Therefore when the state is processed by my components they receive only the default state which is an empty Immutable Map(). However, at some point I receive the store from the server, I call setState from my action_creators and that is processed by my reducer which merges the store into my local store. This entire process is logged using redux-logger. See the associated screenshot. You can see that the local state has changed but the components are not rerendered.

Redux-logger output
<- Component State is what the high-level component receives.

I know my actions and reducers work to some degree because if I merge a local JSON file with my local store the state the component receives is not just an empty Map but contains the full state data. However, this does not mean re-rendering works and I am under the assumption that the state has only been process because it was available before the components were initially called.

Please take a look at my index.js, action_creators.js, reducer.js, and my high-level component Game

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import {createStore, applyMiddleware} from 'redux';
import {Provider} from 'react-redux';
import {setState} from './action_creators';
import io from 'socket.io-client';
import logger from 'redux-logger';

import routes from './routes.js';
import reducer from './reducer';
import InitialState from './initial.json';
import './index.scss';

const socket = io(`${location.protocol}//${location.hostname}:8090`);
const store = createStore(
  reducer,
  applyMiddleware(logger)
);

socket.on('state', state => store.dispatch(setState(state)));
// socket.on('state', state => console.log("From Store", store.getState()));
// socket.on('state',store.dispatch(setState(InitialState)));
// console.log("From JSON",InitialState);

ReactDOM.render(
<Provider store={store}>
    {routes}
</Provider>, document.getElementById('root'));
</code>```

reducer.js

```<code>import {Map} from 'immutable';

export default function(state = Map(), action) {
  switch (action.type) {
    case 'SET_STATE':
      return state.merge(state, action.state);
    default:
      return state;
  }
}
</code>```

action_creators.js

```<code>export function setState(state) {
  return {type: 'SET_STATE',state};
}

export function modIndicator(state, playerId, indicator, modifier) {
  return {type: 'INDICATORS', playerId: playerId, indicator: indicator, modifier: modifier};
}
export function modCollection(state, collection, property, value, op, category) {
  return {
    type:'COLLECTIONS',
    collection:collection,
    property:property,
    value:value,
    op:op,
    category:category};
}
</code>```

Game.js

```<code>import React, {PureComponent, PropTypes} from 'react';
// import Card from '../../Components/Card/index.js';
// import Collection from '../../Components/Collection/index.js';
import Indicator from '../../Components/Indicator/index.js';
import Counter from '../../Components/Counter/index.js';
import {connect} from 'react-redux';
import * as actionCreators from './../../action_creators.js';
import './styles.scss';

export default class Game extends PureComponent {
  render() {
let playersById = this.props.playersById;
let collections = this.props.collections;
let counters = this.props.counters;

let indic_list = [];
let coll_list = [];

//Indicators
playersById.forEach(function(value, key, map){
  indic_list.push(<p className="section-name">{playersById.get(key).get('name')+"'s Indicators"}</p>)
  playersById.get(key).get('indicators').forEach(function(value, key, map){
      indic_list.push(<Indicator label={key}>{value}</Indicator>)
  });
});

//Collections
collections.forEach(function(value, key, map) {
  coll_list.push(<span>{key}: {collections.get(key).get("content").size}</span>);
  collections.get(key).get("control").forEach(function(value, key, map){
      coll_list.push(<span>Control: {value}</span>);
  });
});

return (
    <div className="frame">
      <div className="left-col">
        {indic_list}
      </div>
      <div className="center-col">
        <span className="collections">
          {coll_list}
        </span>
      </div>
      <div className="right-col">
        <div className="counters">
          {counters.map(function(type){
            return <Counter label={type}></Counter>
          })}
        </div>
      </div>
    </div>
  )
  }
}

Game.PropTypes = {
  playersById:  PropTypes.object.isRequired,
  collections: PropTypes.object.isRequired,
  counters: PropTypes.object.isRequired
}
function mapStateToProps(state) {
  console.log("Component State",state);
  return {
    playersById: state.get('playersById'),
    collections: state.get('collections'),
    counters: state.get('counters')
  };
}
export const GameContainer = connect(mapStateToProps, actionCreators)(Game);
</code>```

答:
You have 3 options ahead of you:

1. Set an initial state that your component can use

```<code>import {fromJS} from 'immutable';

const initialState = fromJS({
    playersById: [],
    collections: [],
    counters: []
});

export default function(state = initialState, action) {
  switch (action.type) {
    case 'SET_STATE':
      return state.merge(state, action.state);
    default:
      return state;
  }
}
</code>```

2. Provide some suitable data if the data is missing

```<code>import {List} from 'immutable';

function mapStateToProps(state) {
  console.log("Component State",state);
  return {
    playersById: state.get('playersById') || new List(),
    collections: state.get('collections') || new List(),
    counters: state.get('counters') || new List()
  };
}
</code>```

This might be safer as your state gets completely replaced every time, so this will protect your component if the incoming data is not suitable for rendering

3. Make the component handle the missing data

```<code>render() {

if (!(playersById && collections && counters)) {
    return null; // or a loading spinner?
}

// ... the rest of your render function

}
</code>```

Body:
This issue comes into play because my high-level components are called before I obtain my initial state via a websocket in the form of a redux store. Therefore when the state is processed by my components they receive only the default state which is an empty Immutable Map(). However, at some point I receive the store from the server, I call setState from my action_creators and that is processed by my reducer which merges the store into my local store. This entire process is logged using redux-logger. See the associated screenshot. You can see that the local state has changed but the components are not rerendered.

Redux-logger output
<- Component State is what the high-level component receives.

I know my actions and reducers work to some degree because if I merge a local JSON file with my local store the state the component receives is not just an empty Map but contains the full state data. However, this does not mean re-rendering works and I am under the assumption that the state has only been process because it was available before the components were initially called.

Please take a look at my index.js, action_creators.js, reducer.js, and my high-level component Game

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {createStore, applyMiddleware} from 'redux';
import {Provider} from 'react-redux';
import {setState} from './action_creators';
import io from 'socket.io-client';
import logger from 'redux-logger';

import routes from './routes.js';
import reducer from './reducer';
import InitialState from './initial.json';
import './index.scss';

const socket = io(`${location.protocol}//${location.hostname}:8090`);
const store = createStore(
  reducer,
  applyMiddleware(logger)
);

socket.on('state', state => store.dispatch(setState(state)));
// socket.on('state', state => console.log("From Store", store.getState()));
// socket.on('state',store.dispatch(setState(InitialState)));
// console.log("From JSON",InitialState);

ReactDOM.render(
<Provider store={store}>
    {routes}
</Provider>, document.getElementById('root'));

reducer.js

import {Map} from 'immutable';

export default function(state = Map(), action) {
  switch (action.type) {
    case 'SET_STATE':
      return state.merge(state, action.state);
    default:
      return state;
  }
}

action_creators.js

export function setState(state) {
  return {type: 'SET_STATE',state};
}

export function modIndicator(state, playerId, indicator, modifier) {
  return {type: 'INDICATORS', playerId: playerId, indicator: indicator, modifier: modifier};
}
export function modCollection(state, collection, property, value, op, category) {
  return {
    type:'COLLECTIONS',
    collection:collection,
    property:property,
    value:value,
    op:op,
    category:category};
}

Game.js

import React, {PureComponent, PropTypes} from 'react';
// import Card from '../../Components/Card/index.js';
// import Collection from '../../Components/Collection/index.js';
import Indicator from '../../Components/Indicator/index.js';
import Counter from '../../Components/Counter/index.js';
import {connect} from 'react-redux';
import * as actionCreators from './../../action_creators.js';
import './styles.scss';

export default class Game extends PureComponent {
  render() {
let playersById = this.props.playersById;
let collections = this.props.collections;
let counters = this.props.counters;

let indic_list = [];
let coll_list = [];

//Indicators
playersById.forEach(function(value, key, map){
  indic_list.push(
{playersById.get(key).get('name')+"'s Indicators"}
)
  playersById.get(key).get('indicators').forEach(function(value, key, map){
      indic_list.push(<Indicator label={key}>{value}</Indicator>)
  });
});

//Collections
collections.forEach(function(value, key, map) {
  coll_list.push({key}: {collections.get(key).get("content").size});
  collections.get(key).get("control").forEach(function(value, key, map){
      coll_list.push(Control: {value});
  });
});

return (

        {indic_list}

          {coll_list}

          {counters.map(function(type){
            return <Counter label={type}></Counter>
          })}

  )
  }
}

Game.PropTypes = {
  playersById:  PropTypes.object.isRequired,
  collections: PropTypes.object.isRequired,
  counters: PropTypes.object.isRequired
}
function mapStateToProps(state) {
  console.log("Component State",state);
  return {
    playersById: state.get('playersById'),
    collections: state.get('collections'),
    counters: state.get('counters')
  };
}
export const GameContainer = connect(mapStateToProps, actionCreators)(Game);

Body:
You have 3 options ahead of you:

1. Set an initial state that your component can use

import {fromJS} from 'immutable';

const initialState = fromJS({
    playersById: [],
    collections: [],
    counters: []
});

export default function(state = initialState, action) {
  switch (action.type) {
    case 'SET_STATE':
      return state.merge(state, action.state);
    default:
      return state;
  }
}

2. Provide some suitable data if the data is missing

import {List} from 'immutable';

function mapStateToProps(state) {
  console.log("Component State",state);
  return {
    playersById: state.get('playersById') || new List(),
    collections: state.get('collections') || new List(),
    counters: state.get('counters') || new List()
  };
}

This might be safer as your state gets completely replaced every time, so this will protect your component if the incoming data is not suitable for rendering

3. Make the component handle the missing data

render() {

if (!(playersById && collections && counters)) {
    return null; // or a loading spinner?
}

// ... the rest of your render function

}


来源: stackexchange

问:
How to find if a line intersects a voxel from a set of voxels?
I have an input as set of voxels with their centre's (x,y,z) given. I have a set of lines. I want to find if a line is intersected by any voxel in the given voxel set. (Yes/No Question). The current algorithm I am using is to traverse through the complete voxel set until I found intersection with any voxel. This takes much time. Is it any way to do it faster? </p>

<p>I am finding intersection of a voxel with the line by calculating the distance of the centre of the voxel from the line and checking whether it is less than some small quantity. </p>

答:
If voxel is axis-aligned box, then you can use any line-clipping algorithm to check for intersection.

I'd recommend Liang-Barsky one (checks for intersection with 6 planes)

ContentLicense: CC BY-SA 3.0

Body:
I have an input as set of voxels with their centre's (x,y,z) given. I have a set of lines. I want to find if a line is intersected by any voxel in the given voxel set. (Yes/No Question). The current algorithm I am using is to traverse through the complete voxel set until I found intersection with any voxel. This takes much time. Is it any way to do it faster?

I am finding intersection of a voxel with the line by calculating the distance of the centre of the voxel from the line and checking whether it is less than some small quantity.


问:
CSS3 transitions not working well on div or image
I try to implement, with Javascript, CSS3 transitions in order to gray an image when mouse is not over  and render with colors when mouse is on it.

Here's my code snippet :

```<code>// Create container for image of simulation
var containerImage =  document.createElement('div');
containerImage.className = 'wrap';
elementBodyContent.appendChild(containerImage);

// Create text for imageElement
var textElement = document.createElement('div');
textElement.className = 'text-over-image';
textElement.innerHTML = 'Click to raise simulation';
containerImage.appendChild(textElement);

// Create image of simulation
var imageElement = document.createElement('img');
imageElement.className = 'contrast';
imageElement.width = 700;
imageElement.height = 381;
imageElement.style.cursor = 'pointer'
imageElement.cursor = 'hand';
imageElement.src = 'http://ghujisl.com/Scene.png';
imageElement.onload = function() {
      containerImage.insertBefore(imageElement, textElement);
};
</code>```

and the CSS related :

```<code>    img.contrast
    {
    filter: contrast(0.3);
            -webkit-filter: contrast(0.3);
            -moz-filter: contrast(0.3);
            -o-filter: contrast(0.3);
            -ms-filter: contrast(0.3);

            -webkit-transition: all 0.3s ease-in-out;
            -moz-transition: all 0.3s ease-in-out;
            -o-transition: all 0.3s ease-in-out;
            -ms-transition: all 0.3s ease-in-out;
    transition: all 0.3s ease-in-out;
    }
    img.contrast:hover
    {
    filter: contrast(1);
            -webkit-filter: contrast(1);
            -moz-filter: contrast(1);
            -o-filter: contrast(1);
            -ms-filter: contrast(1);

            -webkit-transform: scale(1.1);
            -moz-transform: scale(1.1);
            -o-transform: scale(1.1);
    transform: scale(1.1);
    }
    .wrap {
    height:auto;
    margin: auto;
    text-align:center;
    position:relative;
    }
   .text-over-image {
        position: absolute;
        margin: auto;
        cursor: pointer;
        top: 0;
        left:0;
        right:0;
        bottom:0;
        color:#fff;
        height:100px;
        }
</code>```

But unfortunately, the transitions are not working correctly. Once I am on the image, sometimes contrast filter is applied and sometimes not.

Moreover, when the mouse is over image, if I stop and restart moving mouse, always over the image, the starting image rendering comes back (I get again gray image whereas mouse is still on image).

You can test this strange behavior on the [following link][1].

I did these tests on Firefox 52 and Chrome Version 57.0.2987.133.

If someone could see what's wrong, it would be nice to show me.

答:
The culprit was your .text-over-image div. As it is absolutely positioned above your image, whenever you put your mouse over it, the mouse event is transferred to that div instead of the image.
An easy fix is to add this to your css:

```<code>.text-over-image{
   pointer-events : none;
   ...
}
</code>```

I just added the above via chrome inspector while visiting your site, and it fixed the problem for me.

Body:
I try to implement, with Javascript, CSS3 transitions in order to gray an image when mouse is not over  and render with colors when mouse is on it.

Here's my code snippet :

// Create container for image of simulation
var containerImage =  document.createElement('div');
containerImage.className = 'wrap';
elementBodyContent.appendChild(containerImage);

// Create text for imageElement
var textElement = document.createElement('div');
textElement.className = 'text-over-image';
textElement.innerHTML = 'Click to raise simulation';
containerImage.appendChild(textElement);

// Create image of simulation
var imageElement = document.createElement('img');
imageElement.className = 'contrast';
imageElement.width = 700;
imageElement.height = 381;
imageElement.style.cursor = 'pointer'
imageElement.cursor = 'hand';
imageElement.src = 'http://ghujisl.com/Scene.png';
imageElement.onload = function() {
      containerImage.insertBefore(imageElement, textElement);
};

and the CSS related :

    img.contrast
    {
    filter: contrast(0.3);
            -webkit-filter: contrast(0.3);
            -moz-filter: contrast(0.3);
            -o-filter: contrast(0.3);
            -ms-filter: contrast(0.3);

            -webkit-transition: all 0.3s ease-in-out;
            -moz-transition: all 0.3s ease-in-out;
            -o-transition: all 0.3s ease-in-out;
            -ms-transition: all 0.3s ease-in-out;
    transition: all 0.3s ease-in-out;
    }
    img.contrast:hover
    {
    filter: contrast(1);
            -webkit-filter: contrast(1);
            -moz-filter: contrast(1);
            -o-filter: contrast(1);
            -ms-filter: contrast(1);

            -webkit-transform: scale(1.1);
            -moz-transform: scale(1.1);
            -o-transform: scale(1.1);
    transform: scale(1.1);
    }
    .wrap {
    height:auto;
    margin: auto;
    text-align:center;
    position:relative;
    }
   .text-over-image {
        position: absolute;
        margin: auto;
        cursor: pointer;
        top: 0;
        left:0;
        right:0;
        bottom:0;
        color:#fff;
        height:100px;
        }

But unfortunately, the transitions are not working correctly. Once I am on the image, sometimes contrast filter is applied and sometimes not.

Moreover, when the mouse is over image, if I stop and restart moving mouse, always over the image, the starting image rendering comes back (I get again gray image whereas mouse is still on image).

You can test this strange behavior on the [following link][1].

I did these tests on Firefox 52 and Chrome Version 57.0.2987.133.

If someone could see what's wrong, it would be nice to show me.

Body:
The culprit was your .text-over-image div. As it is absolutely positioned above your image, whenever you put your mouse over it, the mouse event is transferred to that div instead of the image.
An easy fix is to add this to your css:

.text-over-image{
   pointer-events : none;
   ...
}

I just added the above via chrome inspector while visiting your site, and it fixed the problem for me.


问:
javascript: How can I round a number to the nearest 10 cents?
I want to round '189.46' to 189.5

Here's an example if we are starting with the number as a string. Can someone please tell me why my method isn't working and what the correct way to do it is?

```<code>Math.round(parseFloat('189.46')).toFixed(1);
</code>```

答:
JavaScript's Math object provides a method for rounding to whole numbers.

One of the most common solutions for rounding to a decimal place is to use...
Number.prototype.toFixed()

So... try this:
`

```<code>var x = '189.46';
var k = parseFloat(x).toFixed(1);  //k = 189.5
var y = parseFloat(k); //y = 189.5
//typeof(k) = string
//typeof(y) = number
</code>```

`

Body:
I want to round '189.46' to 189.5

Here's an example if we are starting with the number as a string. Can someone please tell me why my method isn't working and what the correct way to do it is?

Math.round(parseFloat('189.46')).toFixed(1);

Body:
JavaScript's Math object provides a method for rounding to whole numbers.

One of the most common solutions for rounding to a decimal place is to use...
Number.prototype.toFixed()

So... try this:
`

var x = '189.46';
var k = parseFloat(x).toFixed(1);  //k = 189.5
var y = parseFloat(k); //y = 189.5
//typeof(k) = string
//typeof(y) = number

`


问:
Unexpected token o in JSON at position 0 at JSON.parse using angular
I have looked at simular threads, but to no success. What I'm trying to do is update my localstorage through an update function. The functions look as follows:

The code to make the variables to call:

```<code>var localProfile = JSON.parse(localStorage.getItem("profile"));

if(localProfile != undefined && localProfile.length>0)
{ this.profiles = localProfile; }

else {
    this.profile = [
        { id: "1526", name: "berserk",      password: "berserk",    age: "31",          gender: "male"},
        { id: "1358", name: "Johnathan",    password: "test",       age: "17",          gender: "male"},
        { id: "2539", name: "Britney",      password: "test",       age: "18",          gender: "female"},
        { id: "1486", name: "Kevin",        password: "test",       age: "7",           gender: "male"},
        { id: "7777", name: "jesus",        password: "holy",       age: "unknown",     gender: "male"},
        { id: "6666", name: "satan",        password: "hell",       age: "unknown",     gender: "unknown"}
    ];
}
</code>```

The code to update the variable:

```<code>this.updateProfile = function(profile) {
    profile.updating = false;
    console.log(profile);
    localStorage.setItem("profile", profile);
}
</code>```

As I noted in the title I am currently using Angular. I have used the console.log(-line and the response seems to be exactly what it's supposed to be. I have tried using JSON.parse( and JSON.stringify as well as a couple of other combinations. I seem to get either the error above or another error when trying to reload the page. Apperently I either cannot execute the statement, or I end up corrupting the data so reloading the page returns a simular error.

In case the data in variable profile is in doubt:

```<code>Array [ Object, Object, Object, Object, Object, Object ]
</code>```

And when taking a closer look at the data:

```<code>age:"17"
gender:"male"
id:"1358"
name:"johnathan"
password:"test"
</code>```

The other object looks identical with no weird defaults in them. I already took care of the $$hashkey just incase that was the problem.

Any help on how to execute the call correctly is greatly apreciated and if the information is insufficient please do tell.

答:
The problem is your not using JSON.stringify when saving your data. So when you are parsing from localStorage its not json.

Add a factory to be used across your application that handles JSON.parse() and JSON.stringify()

```<code>.factory('LocalStorageUtil', function() {
  return {
    get: get,
    set: set,
    remove: remove
  }

  function get(key) {
    return JSON.parse(localStorage.getItem(key));
  }

  function set(key, val) {
    localStorage.setItem(key, JSON.stringify(val));
  }

  function remove(key) {
    return localStorage.removeItem(key);
  }
})
</code>```

Here is a JS Bin tiny sample app using this LocalStorageUtil.

http://jsbin.com/fijagiy/2/edit?js,output

Body:
I have looked at simular threads, but to no success. What I'm trying to do is update my localstorage through an update function. The functions look as follows:

The code to make the variables to call:

var localProfile = JSON.parse(localStorage.getItem("profile"));

if(localProfile != undefined && localProfile.length>0)
{ this.profiles = localProfile; }

else {
    this.profile = [
        { id: "1526", name: "berserk",      password: "berserk",    age: "31",          gender: "male"},
        { id: "1358", name: "Johnathan",    password: "test",       age: "17",          gender: "male"},
        { id: "2539", name: "Britney",      password: "test",       age: "18",          gender: "female"},
        { id: "1486", name: "Kevin",        password: "test",       age: "7",           gender: "male"},
        { id: "7777", name: "jesus",        password: "holy",       age: "unknown",     gender: "male"},
        { id: "6666", name: "satan",        password: "hell",       age: "unknown",     gender: "unknown"}
    ];
}

The code to update the variable:

this.updateProfile = function(profile) {
    profile.updating = false;
    console.log(profile);
    localStorage.setItem("profile", profile);
}

As I noted in the title I am currently using Angular. I have used the console.log(-line and the response seems to be exactly what it's supposed to be. I have tried using JSON.parse( and JSON.stringify as well as a couple of other combinations. I seem to get either the error above or another error when trying to reload the page. Apperently I either cannot execute the statement, or I end up corrupting the data so reloading the page returns a simular error.

In case the data in variable profile is in doubt:

Array [ Object, Object, Object, Object, Object, Object ]

And when taking a closer look at the data:

age:"17"
gender:"male"
id:"1358"
name:"johnathan"
password:"test"

The other object looks identical with no weird defaults in them. I already took care of the $$hashkey just incase that was the problem.

Any help on how to execute the call correctly is greatly apreciated and if the information is insufficient please do tell.

Body:
The problem is your not using JSON.stringify when saving your data. So when you are parsing from localStorage its not json.

Add a factory to be used across your application that handles JSON.parse() and JSON.stringify()

.factory('LocalStorageUtil', function() {
  return {
    get: get,
    set: set,
    remove: remove
  }

  function get(key) {
    return JSON.parse(localStorage.getItem(key));
  }

  function set(key, val) {
    localStorage.setItem(key, JSON.stringify(val));
  }

  function remove(key) {
    return localStorage.removeItem(key);
  }
})

Here is a JS Bin tiny sample app using this LocalStorageUtil.

http://jsbin.com/fijagiy/2/edit?js,output


问:
Another mysterious failure
I am getting this in the function log. Haven't seen this pattern before and don't know what it means nor how to correct it. Only change to function was to change a regex expression.</p>

```<code>2017-04-01T23:45:25.431 Function completed (Failure, Id=25de0b34-b138-4390-af0c-f8f6ed68fd48)
2017-04-01T23:45:25.509 Exception while executing function: Functions.FormatEmail. mscorlib: Could not load file or assembly '0 bytes loaded from Microsoft.Azure.WebJobs.Script, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format. Bad IL format.
2017-04-01T23:45:25.619 mscorlib: Exception while executing function: Functions.FormatEmail. mscorlib: Could not load file or assembly '0 bytes loaded from Microsoft.Azure.WebJobs.Script, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format. Bad IL format.
2017-04-01T23:45:25.728 mscorlib: Exception while executing function: Functions.FormatEmail. mscorlib: Could not load file or assembly '0 bytes loaded from Microsoft.Azure.WebJobs.Script, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format. Bad IL format.
2017-04-01T23:45:25.759 mscorlib: Exception while executing function: Functions.FormatEmail. mscorlib: Could not load file or assembly '0 bytes loaded from Microsoft.Azure.WebJobs.Script, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format. Bad IL format.
2017-04-01T23:45:25.791 mscorlib: Exception while executing function: Functions.FormatEmail. mscorlib: Could not load file or assembly '0 bytes loaded from Microsoft.Azure.WebJobs.Script, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format. Bad IL format.
2017-04-01T23:45:25.916 mscorlib: Exception while executing function: Functions.FormatEmail. mscorlib: Could not load file or assembly '0 bytes loaded from Microsoft.Azure.WebJobs.Script, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format. Bad IL format.
2017-04-01T23:45:25.979 Function started (Id=ac8c2552-e697-4e65-bd1a-33e5b9a3b802)
2017-04-01T23:45:25.979 Function completed (Failure, Id=ac8c2552-e697-4e65-bd1a-33e5b9a3b802)
2017-04-01T23:45:26.073 mscorlib: Exception while executing function: Functions.FormatEmail. mscorlib: Could not load file or assembly '0 bytes loaded from Microsoft.Azure.WebJobs.Script, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format. Bad IL format.
2017-04-01T23:45:26.104 Exception while executing function: Functions.FormatEmail. mscorlib: Could not load file or assembly '0 bytes loaded from Microsoft.Azure.WebJobs.Script, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format. Bad IL format.
</code>```

答: You may be mixing 32bit and 64bit assemblies that are getting copied up to your function app. Ensure in you build configuration that you are building all the same.</p>

Title: Another mysterious failure

Body:
I am getting this in the function log. Haven't seen this pattern before and don't know what it means nor how to correct it. Only change to function was to change a regex expression.

2017-04-01T23:45:25.431 Function completed (Failure, Id=25de0b34-b138-4390-af0c-f8f6ed68fd48)
2017-04-01T23:45:25.509 Exception while executing function: Functions.FormatEmail. mscorlib: Could not load file or assembly '0 bytes loaded from Microsoft.Azure.WebJobs.Script, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format. Bad IL format.
2017-04-01T23:45:25.619 mscorlib: Exception while executing function: Functions.FormatEmail. mscorlib: Could not load file or assembly '0 bytes loaded from Microsoft.Azure.WebJobs.Script, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format. Bad IL format.
2017-04-01T23:45:25.728 mscorlib: Exception while executing function: Functions.FormatEmail. mscorlib: Could not load file or assembly '0 bytes loaded from Microsoft.Azure.WebJobs.Script, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format. Bad IL format.
2017-04-01T23:45:25.759 mscorlib: Exception while executing function: Functions.FormatEmail. mscorlib: Could not load file or assembly '0 bytes loaded from Microsoft.Azure.WebJobs.Script, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format. Bad IL format.
2017-04-01T23:45:25.791 mscorlib: Exception while executing function: Functions.FormatEmail. mscorlib: Could not load file or assembly '0 bytes loaded from Microsoft.Azure.WebJobs.Script, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format. Bad IL format.
2017-04-01T23:45:25.916 mscorlib: Exception while executing function: Functions.FormatEmail. mscorlib: Could not load file or assembly '0 bytes loaded from Microsoft.Azure.WebJobs.Script, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format. Bad IL format.
2017-04-01T23:45:25.979 Function started (Id=ac8c2552-e697-4e65-bd1a-33e5b9a3b802)
2017-04-01T23:45:25.979 Function completed (Failure, Id=ac8c2552-e697-4e65-bd1a-33e5b9a3b802)
2017-04-01T23:45:26.073 mscorlib: Exception while executing function: Functions.FormatEmail. mscorlib: Could not load file or assembly '0 bytes loaded from Microsoft.Azure.WebJobs.Script, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format. Bad IL format.
2017-04-01T23:45:26.104 Exception while executing function: Functions.FormatEmail. mscorlib: Could not load file or assembly '0 bytes loaded from Microsoft.Azure.WebJobs.Script, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format. Bad IL format.


问:
how does work the creation of indexes when the index is part of a closure?
In the following code I'm confused about the line with the comment "here!":

```<code>var foo = [];
for(var i = 0; i < 10; i++){
    (function(){
     var y = i;
     foo[i] = function(){return y;} //here!
 })();
}
</code>```

Why the "i" value creates the indexes of "foo" correctly? At the end when we try to consult its value is 10. So, why don'tnwe have something like:

content of foo: foo[10] //10 (having only this position in this array)

I understand that we have a closure over "i", because we are making a reference related to another scope, but what I don't understand is why the indexes for "foo" were created correctly having a closure over the "i" variable.

答:
The reason that it works is that your inner function is called synchronously from within the loop.

Common problems occur -- with referencing an outer index in a nested function -- when that function is called asynchronously, or at least after the loop has been executed completely, which is not your case.

Example where it would go wrong:

```<code>var foo = [];
for(var i = 0; i < 10; i++){
    setTimeout(function(){
        var y = i;
        foo[i] = function(){return y;} //here!
    }, 0);
}
</code>```

Body:
In the following code I'm confused about the line with the comment "here!":

var foo = [];
for(var i = 0; i < 10; i++){
    (function(){
     var y = i;
     foo[i] = function(){return y;} //here!
 })();
}

Why the "i" value creates the indexes of "foo" correctly? At the end when we try to consult its value is 10. So, why don'tnwe have something like:

content of foo: foo[10] //10 (having only this position in this array)

I understand that we have a closure over "i", because we are making a reference related to another scope, but what I don't understand is why the indexes for "foo" were created correctly having a closure over the "i" variable.

Body:
The reason that it works is that your inner function is called synchronously from within the loop.

Common problems occur -- with referencing an outer index in a nested function -- when that function is called asynchronously, or at least after the loop has been executed completely, which is not your case.

Example where it would go wrong:

var foo = [];
for(var i = 0; i < 10; i++){
    setTimeout(function(){
        var y = i;
        foo[i] = function(){return y;} //here!
    }, 0);
}


问:
if else loop on Python. Checking a class name with Selenium
I have this appointment system where i have to wait till the link is available. If this link its availble then click it. If not back and foward (beacause the page doesn't let me reload ). And check it again till is available.

```<code>while True:

    if driver.find_element_by_class_name("linkButton"):

            #do somthing

    else:

             driver.back()
             driver.forward()
             #check again.
</code>```

The program doesn't throw any error but when i force the if to be false the else just do nothing.

I can't check it with the link that is not available because in the page is till available that's why i force the if to be false

答:
First of all, the find_element_*() methods don't return true/false, they either return a WebElement instance (which is truthy) or throw a NoSuchElementException exception (or other exception).

The existence check is usually done via find_elements_*() methods which, if an element is not found, would return an empty list, which is falsy:

```<code>while True:
    if driver.find_elements_by_class_name("linkButton"):
        # do something
    else:
        driver.refresh()
</code>```

Note that I think you just meant to refresh() the page instead of going back and forward.

And, you should also add some time delays between the attempts.

Body:
I have this appointment system where i have to wait till the link is available. If this link its availble then click it. If not back and foward (beacause the page doesn't let me reload ). And check it again till is available.

while True:

    if driver.find_element_by_class_name("linkButton"):

            #do somthing

    else:

             driver.back()
             driver.forward()
             #check again.

The program doesn't throw any error but when i force the if to be false the else just do nothing.

I can't check it with the link that is not available because in the page is till available that's why i force the if to be false

Body:
First of all, the find_element_*() methods don't return true/false, they either return a WebElement instance (which is truthy) or throw a NoSuchElementException exception (or other exception).

The existence check is usually done via find_elements_*() methods which, if an element is not found, would return an empty list, which is falsy:

while True:
    if driver.find_elements_by_class_name("linkButton"):
        # do something
    else:
        driver.refresh()

Note that I think you just meant to refresh() the page instead of going back and forward.

And, you should also add some time delays between the attempts.


问:
when should the child object be declared as a member variable of its parent class in qt?
```<code>//disconnect.h
#include <QWidget>
#include <QPushButton>

class Disconnect : public QWidget {

  Q_OBJECT

  public:
    Disconnect(QWidget *parent = 0);

  private slots:
    void onClick();
    void onCheck(int);

  private:
    QPushButton *clickBtn;
};
</code>```

```<code>//disconnect.cpp
#include <QTextStream>
#include <QCheckBox>
#include <QHBoxLayout>
#include "disconnect.h"

Disconnect::Disconnect(QWidget *parent)
    : QWidget(parent) {

  QHBoxLayout *hbox = new QHBoxLayout(this);
  hbox->setSpacing(5);

  clickBtn = new QPushButton("Click", this);
  hbox->addWidget(clickBtn, 0, Qt::AlignLeft | Qt::AlignTop);

  QCheckBox *cb = new QCheckBox("Connect", this);
  cb->setCheckState(Qt::Checked);
  hbox->addWidget(cb, 0, Qt::AlignLeft | Qt::AlignTop);

  connect(clickBtn, &QPushButton::clicked, this, &Disconnect::onClick);
  connect(cb, &QCheckBox::stateChanged, this, &Disconnect::onCheck);
}

void Disconnect::onClick() {

  QTextStream out(stdout);
  out << "Button clicked" << endl;
}

void Disconnect::onCheck(int state) {

  if (state == Qt::Checked) {
    connect(clickBtn, &QPushButton::clicked, this, &Disconnect::onClick);
  } else {
    disconnect(clickBtn, &QPushButton::clicked, this,
        &Disconnect::onClick);
  }
}
</code>```

```<code>//main.cpp
#include <QApplication>
#include "disconnect.h"

int main(int argc, char *argv[]) {

  QApplication app(argc, argv);

  Disconnect window;

  window.resize(250, 150);
  window.setWindowTitle("Disconnect");
  window.show();

  return app.exec();
}
</code>```

In the above code，A Disconnect object has two child object——a QPushButton and a  QcheckBox, but class Disconnect only have a QPushButton pointer, not a QcheckBox pointer. Can anyone tell me when should the child object be declared as a member variable of its parent class in qt?

答:
Can anyone tell me when should the child object be declared as a
  member variable of its parent class in qt?

If you think you will need to call methods on (or otherwise access) the child object from other methods of parent class (as your example code does with clickBtn, referencing it from the onCheck method), then you'll want to create a member variable that is a pointer to that child object, to allow you to do so.

If, on the other hand, you will not need to access the child object outside of the method where it was created, then you can keep your parent class's definition shorter and simpler by declaring the pointer-to-the-child-object as a local variable inside the creating method only.

Body:
//disconnect.h
#include <QWidget>
#include <QPushButton>

class Disconnect : public QWidget {

  Q_OBJECT

  public:
    Disconnect(QWidget *parent = 0);

  private slots:
    void onClick();
    void onCheck(int);

  private:
    QPushButton *clickBtn;
};

//disconnect.cpp
#include <QTextStream>
#include <QCheckBox>
#include <QHBoxLayout>
#include "disconnect.h"

Disconnect::Disconnect(QWidget *parent)
    : QWidget(parent) {

  QHBoxLayout *hbox = new QHBoxLayout(this);
  hbox->setSpacing(5);

  clickBtn = new QPushButton("Click", this);
  hbox->addWidget(clickBtn, 0, Qt::AlignLeft | Qt::AlignTop);

  QCheckBox *cb = new QCheckBox("Connect", this);
  cb->setCheckState(Qt::Checked);
  hbox->addWidget(cb, 0, Qt::AlignLeft | Qt::AlignTop);

  connect(clickBtn, &QPushButton::clicked, this, &Disconnect::onClick);
  connect(cb, &QCheckBox::stateChanged, this, &Disconnect::onCheck);
}

void Disconnect::onClick() {

  QTextStream out(stdout);
  out << "Button clicked" << endl;
}

void Disconnect::onCheck(int state) {

  if (state == Qt::Checked) {
    connect(clickBtn, &QPushButton::clicked, this, &Disconnect::onClick);
  } else {
    disconnect(clickBtn, &QPushButton::clicked, this,
        &Disconnect::onClick);
  }
}

//main.cpp
#include <QApplication>
#include "disconnect.h"

int main(int argc, char *argv[]) {

  QApplication app(argc, argv);

  Disconnect window;

  window.resize(250, 150);
  window.setWindowTitle("Disconnect");
  window.show();

  return app.exec();
}

In the above code，A Disconnect object has two child object——a QPushButton and a  QcheckBox, but class Disconnect only have a QPushButton pointer, not a QcheckBox pointer. Can anyone tell me when should the child object be declared as a member variable of its parent class in qt?


问:
jQuery: 'load more' masonry elements?
I have a few elements on my page which I'm loading 5 at a time.

What I need to do is to animate the loaded elements using animate.css.

To explain this, I've created this fiddle:

https://jsfiddle.net/89v781rL/6/

Scroll down to see the Show more button and click on it to see it in action.

When i load more items, the elements are animated but because they are layed out in a Masonry style, the position of them keep changing which is not what i want. Basically I need to keep the elements in their first position and keep adding/loading more elements.

If you comment out the following CSS code and run the JSFIDDLE, you will see how nicely the elements are layed out and that is how i want them to be when they are loading 5 at a time too:

```<code>#grid li:nth-child(n+6) {
  /*display: none;*/
}
</code>```

what I need to do is to bounce the elements UP using animate.css.

This is my full code:

```<code>$('#sales').click(function() {
$('#grid li').not(':visible').slice(0, 5).slideDown();

$('#grid li').not(':visible').slice(0, 5).addClass('animated bounceInUp');
});
</code>```

Note: I don't want to use any plugins like this

Mainly because it is very big and bloated for my project and it doesn't function properly in my project either.

Could someone please advise on this issue?

EDIT:

Here is another failed attempt to do this:

https://jsfiddle.net/89v781rL/8/

And this one too:

https://jsfiddle.net/89v781rL/9/

答:
TL;DR: Proposed solution.

Simply put, what you want is not possible. At least not how you started it.

But, here's the thing: the reason I got into coding (coming from design background - and also the main reason I answered your question) is because a bunch of web developers told me about a particular design I made, that it's not possible. So I (re)searched and experimented until I found a way.

Ever since, whenever I come to this conclusion, I always translate it to:

It's possible, I'm just doing it wrong™.

In your particular case, you're using a "masonry" technique that's not exactly masonry. It's a column layout technique, called CSS columns. Here's what it does, from a technical point of view:

calculates the width of columns, considering parent total width, columns number and column gutter

calculates the total height of contents, considering the resulting column width

breaks the content into chunks fitting into columns, trying to distribute content equally, respecting any break-inside declarations. Note the  suggestive name of the property value: avoid, it's not forbid or disallow. Based on contents, this rule doesn't always apply.

But, in short, here's how your 2 columns layout renders initially:

```<code>1 4
2 5
3 6
</code>```

When you decide to add more content, it will go through the steps above again, considering the updated content height resulting in:

```<code>1 5
2 6
3 7
4
</code>```

It will calculate possible breaking options and will go for the one that results in the smallest height for the parent element. If two or more result in the same height, most browsers will choose the one that makes the later/last column shorter.

If your content needs to stay into place once rendered, the CSS Columns technique is clearly not an option. So you're looking at techniques using absolute positioning. You have many options, but the notable ones (I'm probably subjective - but is anyone really objective?) are:

Masonry. It comes with the very handy stamp method, specifically designed for your requirement (stick existing elements into place, so adding more content will not re-position existing elements - which could happen occasionally, depending on contents and parent - for example, if you have a list of existing short items and you add a very tall one, it would result in a column much taller than the rest; if stamp wasn't called on existing items, they will be re-positioned so that resulting columns have minimal differences in height)

Isotope - I've never had the chance to use it, but I heard good things about it.

The so-called pinterest layout script. It was written by Evan Sharp, it relies entirely on javascript and absolute positioning (just like Masonry) but is incredibly efficient. He explains how he did it in this SO answer and here's a good tutorial on the technique. If you don't care much about the technical part and are only interested in the juice, I found a light plugin, called Bootstrap Waterfall which, apart from everything linked above, has a production ready usable version.

Everything I wrote so far is what a bit of time and decent search-fu would have gotten you.

The only step left (and the real answer) would be animating each item into view using the required animate.css effect. I chose Bootstrap-waterfall for the layout, but you could as well go with any of the other options. Here it is:

// Included waterfall script as it doesn't load from github for everyone
+function(t){"use strict";function i(i){this.$pins=i,this.tasks=[],this.timerId=null,this.deferred=new t.Deferred}function e(t){this.img=t,this.initialWidth=t.width,this.initialHeight=t.height}function n(i){return this.each(function(){var e=t(this),n=e.data("mystist.waterfall"),s="object"==typeof i&&i;n&&"string"!=typeof i&&n.destroy()&&(n=null),n||e.data("mystist.waterfall",n=new o(this,s)),"string"==typeof i&&n[i]()})}var s=s||{now:Date.now||function(){return(new Date).getTime()},throttle:function(t,i,e){var n,o,r,a=null,h=0;e||(e={});var l=function(){h=e.leading===!1?0:s.now(),a=null,r=t.apply(n,o),a||(n=o=null)};return function(){var u=s.now();h||e.leading!==!1||(h=u);var c=i-(u-h);return n=this,o=arguments,0>=c||c>i?(a&&(clearTimeout(a),a=null),h=u,r=t.apply(n,o),a||(n=o=null)):a||e.trailing===!1||(a=setTimeout(l,c)),r}},debounce:function(t,i,e){var n,o,r,a,h,l=function(){var u=s.now()-a;i>u&&u>=0?n=setTimeout(l,i-u):(n=null,e||(h=t.apply(r,o),n||(r=o=null)))};return function(){r=this,o=arguments,a=s.now();var u=e&&!n;return n||(n=setTimeout(l,i)),u&&(h=t.apply(r,o),r=o=null),h}}},o=function(i,e){this.$element=t(i),this.options=t.extend({},o.DEFAULTS,e),this.id=Math.random().toString().slice(2),this.$fakePin=null,this.$container=null,this.$pins=null,this.pinWidth=null,this.imgWidth=null,this.lefts=[],this.tops=[],this.init().calculateWidth().calculatePosition().sail(),t(window).on("resize.mystist.waterfall"+this.id,s.debounce(t.proxy(function(){t(window).off("scroll.mystist.waterfall"+this.id),this.calculateWidth().calculatePosition().ship(r.getLoadedPins.call(this))},this),777))};o.VERSION="0.2.4",o.DEFAULTS={},o.prototype.init=function(){return this.initPins().initAttributes(),this},o.prototype.initPins=function(){var i=this.$element.children().length>0?this.$element.children().remove():t(this.$element.data("bootstrap-waterfall-template"));return i.each(function(){var i=t(this).find("img:eq(0)");i.length>0&&(t(this).data("bootstrap-waterfall-src",i.attr("src")),i.attr("src","data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="))}),this.$pins=i,this},o.prototype.initAttributes=function(){return this.$fakePin=this.$pins.first().clone(),this.$container=t("
").css("position","relative"),this.$element.html(this.$container),this},o.prototype.calculateWidth=function(){var t=this.$fakePin.clone();return this.$container.append(t.css("opacity",0)),this.pinWidth=t.outerWidth(!0),this.imgWidth=t.find("img:eq(0)").css("width","100%").width(),t.remove(),this},o.prototype.calculatePosition=function(){for(var t=parseInt(this.$container.width()/this.pinWidth,10),i=[],e=[],n=0;t>n;n++)i.push(n*this.pinWidth),e.push(0);return this.lefts=i,this.tops=e,this},o.prototype.sail=function(){var e=r.getToLoadPins.call(this),n=new i(e);return n.load().run().deferred.done(t.proxy(function(){this.ship(e)},this)),this},o.prototype.ship=function(i){return this.render(i).updateHeight(),t(window).on("scroll.mystist.waterfall"+this.id,s.throttle(t.proxy(function(){r.isWantMore.call(this)&&(t(window).off("scroll.mystist.waterfall"+this.id),this.sail())},this),500)),this},o.prototype.render=function(i){var e=this;return i.each(function(){e.placePin(t(this))}),this},o.prototype.placePin=function(t){var i=a.indexOf(this.tops,Math.min.apply(null,this.tops)),e=r.getPosition.call(this,i);return t.css({position:"absolute",left:e.left,top:e.top}),t.data("bootstrap-waterfall-pin")&&r.setImageHeight.call(this,t),t.data("bootstrap-waterfall-src")&&(r.makeImageAvailable.call(this,t),t.removeData("bootstrap-waterfall-src")),this.$container.append(t),r.updatePosition.call(this,i,t),this},o.prototype.updateHeight=function(){var t=a.indexOf(this.tops,Math.max.apply(null,this.tops));return this.$container.height(this.tops[t]),this},o.prototype.destroy=function(){return t(window).off("scroll.mystist.waterfall"+this.id),t(window).off("resize.mystist.waterfall"+this.id),this.$element.empty().removeData("mystist.waterfall"),this};var r={getToLoadPins:function(){var i=parseInt(this.$container.width()/this.pinWidth,10),e=3*i,n=this.$pins.map(function(){return t(this).find("img").length>0&&t(this).data("bootstrap-waterfall-src")?t(this):void 0});return n.slice(0,e)},getLoadedPins:function(){var i=this.$pins.map(function(){return t(this).find("img").length>0&&!t(this).data("bootstrap-waterfall-src")?t(this):void 0});return i},isWantMore:function(){return t(window).scrollTop()+t(window).height()>a.getDocHeight()-377?!0:!1},getPosition:function(t){var i={left:this.lefts[t],top:this.tops[t]};return i},setImageHeight:function(t){var i=t.data("bootstrap-waterfall-pin"),e=this.imgWidth*i.img.height/i.img.width;t.find("img:eq(0)").css({height:e,width:"auto"})},makeImageAvailable:function(t){t.find("img:eq(0)").attr("src",t.data("bootstrap-waterfall-src"))},updatePosition:function(t,i){this.tops[t]+=i.outerHeight(!0)}};i.prototype.load=function(){var i=this;return this.$pins.each(function(){var n=new Image;n.src=t(this).data("bootstrap-waterfall-src");var s=new e(n);i.tasks.push(s),t(this).data("bootstrap-waterfall-pin",s)}),this},i.prototype.run=function(){return this.timerId=setInterval(t.proxy(function(){this.isDone()?this.stop():this.check()},this),40),this},i.prototype.isDone=function(){return 0===this.tasks.length?!0:!1},i.prototype.stop=function(){clearInterval(this.timerId),this.timerId=null,this.deferred.resolve()},i.prototype.check=function(){for(var t=0;t<this.tasks.length;t++){var i=this.tasks[t];i.isLoaded()&&this.tasks.splice(t--,1)}},e.prototype.isLoaded=function(){return this.img.width!==this.initialWidth||this.img.height!==this.initialHeight||this.img.width*this.img.height>1024?!0:!1};var a={getDocHeight:function(){var t=document;return Math.max(t.body.scrollHeight,t.documentElement.scrollHeight,t.body.offsetHeight,t.documentElement.offsetHeight,t.body.clientHeight,t.documentElement.clientHeight)},indexOf:function(t,i){if(null==t)return-1;for(var e=0,n=t.length;n>e;e++)if(t[e]===i)return e;return-1}},h=t.fn.waterfall;t.fn.waterfall=n,t.fn.waterfall.Constructor=o,t.fn.waterfall.noConflict=function(){return t.fn.waterfall=h,this}}(jQuery);
// note waterfall should normally be linked as resource in your project

$('#waterfall').data('bootstrap-waterfall-template', $('#waterfall-template').html());
let wf = $('#waterfall').waterfall();

let fader = {
  wh: $(window).height(),
  full: function() {
   $('#waterfall .pin').each(function(i, e) {
      (function(i, e) {
        setTimeout(function() {
          fader.check(e)
        }, i * 150);
      })(i, e)
    })
  },
  check: function(e) {
    if (fader.wh > e.getBoundingClientRect().top + 60) {
      $(e).addClass('inView');
      setTimeout(function() { $(e).addClass('fix') }, 750)
    }
  },
  resize:function(){
    fader.wh = $(window).height();
    fader.full();
  },
  light: function() {
    let fst = $('#waterfall .pin:not(".inView")').eq(0);
    if (fst.is('.pin')) {
      fader.check(fst[0])
    }
  }
};

setTimeout(function() { fader.full() }, 210);
$(window)
  .on('scroll', fader.light)
  .on('resize', _.throttle(fader.resize,
    500,{leading:false,trailing:true})
  );```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#waterfall .pin {
  width: calc(50% - 4px);
  opacity: 0;
  animation-duration: 0.75s;
  animation-fill-mode: both; }
#waterfall .pin.inView {
  opacity: 1;
  animation-name: bounceInUp; }
#waterfall .pin.inView.fix {
  animation: none; }
#waterfall .pin a {
  display: block;
  padding: 4px 4px 8px; }

* {
  box-sizing: border-box; }

.container {
  text-align: center; }
.container #waterfall {
  max-width: 800px;
  margin: 0 auto; }

@keyframes bounceInUp {
  from, 60%, 75%, 90%, to {
    animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);   }
  from {
    opacity: 0;
    transform: translate3d(0, 3000px, 0);   }
  60% {
    opacity: 1;
    transform: translate3d(0, -20px, 0);   }
  75% {
    transform: translate3d(0, 10px, 0);   }
  90% {
    transform: translate3d(0, -5px, 0);   }
  to {
    transform: translate3d(0, 0, 0);   }
}</code>```

```

Its main advantage (and why I chose this route) is it lazy-loads the images just before they scroll into view, which means you no longer need a button to load more. You can just put all the images in the template

Title: jQuery: 'load more' masonry elements?

Body:
I have a few elements on my page which I'm loading 5 at a time.

What I need to do is to animate the loaded elements using animate.css.

To explain this, I've created this fiddle:

https://jsfiddle.net/89v781rL/6/

Scroll down to see the Show more button and click on it to see it in action.

When i load more items, the elements are animated but because they are layed out in a Masonry style, the position of them keep changing which is not what i want. Basically I need to keep the elements in their first position and keep adding/loading more elements.

If you comment out the following CSS code and run the JSFIDDLE, you will see how nicely the elements are layed out and that is how i want them to be when they are loading 5 at a time too:

#grid li:nth-child(n+6) {
  /*display: none;*/
}

what I need to do is to bounce the elements UP using animate.css.

This is my full code:

$('#sales').click(function() {
$('#grid li').not(':visible').slice(0, 5).slideDown();

$('#grid li').not(':visible').slice(0, 5).addClass('animated bounceInUp');
});

Note: I don't want to use any plugins like this

Mainly because it is very big and bloated for my project and it doesn't function properly in my project either.

Could someone please advise on this issue?

EDIT:

Here is another failed attempt to do this:

https://jsfiddle.net/89v781rL/8/

And this one too:

https://jsfiddle.net/89v781rL/9/

Body:
TL;DR: Proposed solution.

Simply put, what you want is not possible. At least not how you started it.

But, here's the thing: the reason I got into coding (coming from design background - and also the main reason I answered your question) is because a bunch of web developers told me about a particular design I made, that it's not possible. So I (re)searched and experimented until I found a way.

Ever since, whenever I come to this conclusion, I always translate it to:

It's possible, I'm just doing it wrong™.

In your particular case, you're using a "masonry" technique that's not exactly masonry. It's a column layout technique, called CSS columns. Here's what it does, from a technical point of view:

calculates the width of columns, considering parent total width, columns number and column gutter

calculates the total height of contents, considering the resulting column width

breaks the content into chunks fitting into columns, trying to distribute content equally, respecting any break-inside declarations. Note the  suggestive name of the property value: avoid, it's not forbid or disallow. Based on contents, this rule doesn't always apply.

But, in short, here's how your 2 columns layout renders initially:

1 4
2 5
3 6

When you decide to add more content, it will go through the steps above again, considering the updated content height resulting in:

1 5
2 6
3 7
4

It will calculate possible breaking options and will go for the one that results in the smallest height for the parent element. If two or more result in the same height, most browsers will choose the one that makes the later/last column shorter.

If your content needs to stay into place once rendered, the CSS Columns technique is clearly not an option. So you're looking at techniques using absolute positioning. You have many options, but the notable ones (I'm probably subjective - but is anyone really objective?) are:

Masonry. It comes with the very handy stamp method, specifically designed for your requirement (stick existing elements into place, so adding more content will not re-position existing elements - which could happen occasionally, depending on contents and parent - for example, if you have a list of existing short items and you add a very tall one, it would result in a column much taller than the rest; if stamp wasn't called on existing items, they will be re-positioned so that resulting columns have minimal differences in height)

Isotope - I've never had the chance to use it, but I heard good things about it.

The so-called pinterest layout script. It was written by Evan Sharp, it relies entirely on javascript and absolute positioning (just like Masonry) but is incredibly efficient. He explains how he did it in this SO answer and here's a good tutorial on the technique. If you don't care much about the technical part and are only interested in the juice, I found a light plugin, called Bootstrap Waterfall which, apart from everything linked above, has a production ready usable version.

Everything I wrote so far is what a bit of time and decent search-fu would have gotten you.

The only step left (and the real answer) would be animating each item into view using the required animate.css effect. I chose Bootstrap-waterfall for the layout, but you could as well go with any of the other options. Here it is:

// Included waterfall script as it doesn't load from github for everyone
+function(t){"use strict";function i(i){this.$pins=i,this.tasks=[],this.timerId=null,this.deferred=new t.Deferred}function e(t){this.img=t,this.initialWidth=t.width,this.initialHeight=t.height}function n(i){return this.each(function(){var e=t(this),n=e.data("mystist.waterfall"),s="object"==typeof i&&i;n&&"string"!=typeof i&&n.destroy()&&(n=null),n||e.data("mystist.waterfall",n=new o(this,s)),"string"==typeof i&&n[i]()})}var s=s||{now:Date.now||function(){return(new Date).getTime()},throttle:function(t,i,e){var n,o,r,a=null,h=0;e||(e={});var l=function(){h=e.leading===!1?0:s.now(),a=null,r=t.apply(n,o),a||(n=o=null)};return function(){var u=s.now();h||e.leading!==!1||(h=u);var c=i-(u-h);return n=this,o=arguments,0>=c||c>i?(a&&(clearTimeout(a),a=null),h=u,r=t.apply(n,o),a||(n=o=null)):a||e.trailing===!1||(a=setTimeout(l,c)),r}},debounce:function(t,i,e){var n,o,r,a,h,l=function(){var u=s.now()-a;i>u&&u>=0?n=setTimeout(l,i-u):(n=null,e||(h=t.apply(r,o),n||(r=o=null)))};return function(){r=this,o=arguments,a=s.now();var u=e&&!n;return n||(n=setTimeout(l,i)),u&&(h=t.apply(r,o),r=o=null),h}}},o=function(i,e){this.$element=t(i),this.options=t.extend({},o.DEFAULTS,e),this.id=Math.random().toString().slice(2),this.$fakePin=null,this.$container=null,this.$pins=null,this.pinWidth=null,this.imgWidth=null,this.lefts=[],this.tops=[],this.init().calculateWidth().calculatePosition().sail(),t(window).on("resize.mystist.waterfall"+this.id,s.debounce(t.proxy(function(){t(window).off("scroll.mystist.waterfall"+this.id),this.calculateWidth().calculatePosition().ship(r.getLoadedPins.call(this))},this),777))};o.VERSION="0.2.4",o.DEFAULTS={},o.prototype.init=function(){return this.initPins().initAttributes(),this},o.prototype.initPins=function(){var i=this.$element.children().length>0?this.$element.children().remove():t(this.$element.data("bootstrap-waterfall-template"));return i.each(function(){var i=t(this).find("img:eq(0)");i.length>0&&(t(this).data("bootstrap-waterfall-src",i.attr("src")),i.attr("src","data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="))}),this.$pins=i,this},o.prototype.initAttributes=function(){return this.$fakePin=this.$pins.first().clone(),this.$container=t("<div />").css("position","relative"),this.$element.html(this.$container),this},o.prototype.calculateWidth=function(){var t=this.$fakePin.clone();return this.$container.append(t.css("opacity",0)),this.pinWidth=t.outerWidth(!0),this.imgWidth=t.find("img:eq(0)").css("width","100%").width(),t.remove(),this},o.prototype.calculatePosition=function(){for(var t=parseInt(this.$container.width()/this.pinWidth,10),i=[],e=[],n=0;t>n;n++)i.push(n*this.pinWidth),e.push(0);return this.lefts=i,this.tops=e,this},o.prototype.sail=function(){var e=r.getToLoadPins.call(this),n=new i(e);return n.load().run().deferred.done(t.proxy(function(){this.ship(e)},this)),this},o.prototype.ship=function(i){return this.render(i).updateHeight(),t(window).on("scroll.mystist.waterfall"+this.id,s.throttle(t.proxy(function(){r.isWantMore.call(this)&&(t(window).off("scroll.mystist.waterfall"+this.id),this.sail())},this),500)),this},o.prototype.render=function(i){var e=this;return i.each(function(){e.placePin(t(this))}),this},o.prototype.placePin=function(t){var i=a.indexOf(this.tops,Math.min.apply(null,this.tops)),e=r.getPosition.call(this,i);return t.css({position:"absolute",left:e.left,top:e.top}),t.data("bootstrap-waterfall-pin")&&r.setImageHeight.call(this,t),t.data("bootstrap-waterfall-src")&&(r.makeImageAvailable.call(this,t),t.removeData("bootstrap-waterfall-src")),this.$container.append(t),r.updatePosition.call(this,i,t),this},o.prototype.updateHeight=function(){var t=a.indexOf(this.tops,Math.max.apply(null,this.tops));return this.$container.height(this.tops[t]),this},o.prototype.destroy=function(){return t(window).off("scroll.mystist.waterfall"+this.id),t(window).off("resize.mystist.waterfall"+this.id),this.$element.empty().removeData("mystist.waterfall"),this};var r={getToLoadPins:function(){var i=parseInt(this.$container.width()/this.pinWidth,10),e=3*i,n=this.$pins.map(function(){return t(this).find("img").length>0&&t(this).data("bootstrap-waterfall-src")?t(this):void 0});return n.slice(0,e)},getLoadedPins:function(){var i=this.$pins.map(function(){return t(this).find("img").length>0&&!t(this).data("bootstrap-waterfall-src")?t(this):void 0});return i},isWantMore:function(){return t(window).scrollTop()+t(window).height()>a.getDocHeight()-377?!0:!1},getPosition:function(t){var i={left:this.lefts[t],top:this.tops[t]};return i},setImageHeight:function(t){var i=t.data("bootstrap-waterfall-pin"),e=this.imgWidth*i.img.height/i.img.width;t.find("img:eq(0)").css({height:e,width:"auto"})},makeImageAvailable:function(t){t.find("img:eq(0)").attr("src",t.data("bootstrap-waterfall-src"))},updatePosition:function(t,i){this.tops[t]+=i.outerHeight(!0)}};i.prototype.load=function(){var i=this;return this.$pins.each(function(){var n=new Image;n.src=t(this).data("bootstrap-waterfall-src");var s=new e(n);i.tasks.push(s),t(this).data("bootstrap-waterfall-pin",s)}),this},i.prototype.run=function(){return this.timerId=setInterval(t.proxy(function(){this.isDone()?this.stop():this.check()},this),40),this},i.prototype.isDone=function(){return 0===this.tasks.length?!0:!1},i.prototype.stop=function(){clearInterval(this.timerId),this.timerId=null,this.deferred.resolve()},i.prototype.check=function(){for(var t=0;t<this.tasks.length;t++){var i=this.tasks[t];i.isLoaded()&&this.tasks.splice(t--,1)}},e.prototype.isLoaded=function(){return this.img.width!==this.initialWidth||this.img.height!==this.initialHeight||this.img.width*this.img.height>1024?!0:!1};var a={getDocHeight:function(){var t=document;return Math.max(t.body.scrollHeight,t.documentElement.scrollHeight,t.body.offsetHeight,t.documentElement.offsetHeight,t.body.clientHeight,t.documentElement.clientHeight)},indexOf:function(t,i){if(null==t)return-1;for(var e=0,n=t.length;n>e;e++)if(t[e]===i)return e;return-1}},h=t.fn.waterfall;t.fn.waterfall=n,t.fn.waterfall.Constructor=o,t.fn.waterfall.noConflict=function(){return t.fn.waterfall=h,this}}(jQuery);
// note waterfall should normally be linked as resource in your project

$('#waterfall').data('bootstrap-waterfall-template', $('#waterfall-template').html());
let wf = $('#waterfall').waterfall();

let fader = {
  wh: $(window).height(),
  full: function() {
   $('#waterfall .pin').each(function(i, e) {
      (function(i, e) {
        setTimeout(function() {
          fader.check(e)
        }, i * 150);
      })(i, e)
    })
  },
  check: function(e) {
    if (fader.wh > e.getBoundingClientRect().top + 60) {
      $(e).addClass('inView');
      setTimeout(function() { $(e).addClass('fix') }, 750)
    }
  },
  resize:function(){
    fader.wh = $(window).height();
    fader.full();
  },
  light: function() {
    let fst = $('#waterfall .pin:not(".inView")').eq(0);
    if (fst.is('.pin')) {
      fader.check(fst[0])
    }
  }
};

setTimeout(function() { fader.full() }, 210);
$(window)
  .on('scroll', fader.light)
  .on('resize', _.throttle(fader.resize,
    500,{leading:false,trailing:true})
  );

#waterfall .pin {
  width: calc(50% - 4px);
  opacity: 0;
  animation-duration: 0.75s;
  animation-fill-mode: both; }
#waterfall .pin.inView {
  opacity: 1;
  animation-name: bounceInUp; }
#waterfall .pin.inView.fix {
  animation: none; }
#waterfall .pin a {
  display: block;
  padding: 4px 4px 8px; }

* {
  box-sizing: border-box; }

.container {
  text-align: center; }
.container #waterfall {
  max-width: 800px;
  margin: 0 auto; }

@keyframes bounceInUp {
  from, 60%, 75%, 90%, to {
    animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);   }
  from {
    opacity: 0;
    transform: translate3d(0, 3000px, 0);   }
  60% {
    opacity: 1;
    transform: translate3d(0, -20px, 0);   }
  75% {
    transform: translate3d(0, 10px, 0);   }
  90% {
    transform: translate3d(0, -5px, 0);   }
  to {
    transform: translate3d(0, 0, 0);   }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

<script id="waterfall-template" type="text/template">
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/1.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/2.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/3.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/4.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/5.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/6.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/7.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/8.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/9.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/10.png" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/11.png" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/12.png" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/2.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/6.jpg">
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/1.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/3.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/2.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/4.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/5.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/6.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/7.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/8.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/9.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/10.png" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/11.png" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/12.png" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/2.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/6.jpg">
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/1.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/2.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/3.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/4.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/5.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/6.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/7.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/8.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/9.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/10.png" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/11.png" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/12.png" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/2.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/6.jpg">
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/1.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/3.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/2.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/4.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/5.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/6.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/7.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/8.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/9.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/10.png" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/11.png" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/12.png" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/2.jpg" />
    </a>
  </div>
  <div class="pin">
    <a href="javascript:;">
      <img src="https://tympanus.net/Development/GridLoadingEffects/images/6.jpg">
    </a>
  </div>
</script>
<div class="container">
  <div id="waterfall"></div>
</div>

Its main advantage (and why I chose this route) is it lazy-loads the images just before they scroll into view, which means you no longer need a button to load more. You can just put all the images in the template <script> tag (read the plugin docs - scroll to Q&A - to see why it recommends adding markup like that).

I've also singled out the BounceInUp animation from animate.css so you don't need to load it.

Note the CSS needs prefixing and, if you want it, the fiddle has the SCSS.

As a general rule I tried to keep it as light as possible, especially in terms of javascript listeners (on scroll I'm only listening to the position of the next item in the list, not to all).

Intended as proof of concept, for pointing in the right direction.

<s>I know what I did is not exactly what you asked (in the sense it doesn't allow you to add more items after first calculation - unfortunately, Bootstrap Waterfall doesn't currently have an update() or addItems() method and I really think they should add one, without recalculating existing pins</s> -

This is no longer true: Mystist, author of bootstrap-waterfall.js has responded to my github request and added the method. I now updated the jsFiddle by adding an add more button to it and it works as expected. Huge thumb up for Mystist from me). Of course, you will probably need to adapt the script to your project's particular case, to how you're bringing the new items in. In the jsFiddle I chose to make a function that generates a new <script> template on the fly and adds pins randomly to it.

Regardless, here are the principles to follow with this layout:

Have an absolute positioning method for placing your items

Hide all items on load. Animate the visible ones into view (staggered) with your desired effect.

Place a lock on all visible ones, to cancel any animation effects on resize (I used fix class).

Place a listener on scroll and check if the next not-visible item has entered view. Animate it when it does and .fix it after end of animation.


问:
How to do a GitHub pull request
How do I create and/or send a pull request to another repository hosted on GitHub?</p>

答:
I've started a project to help people making their first GitHub pull request. You can do the hands-on tutorial to make your first PR here

The workflow is simple as

Fork the repo in github

Get clone url by clicking on clone repo button

Go to terminal and run git clone <clone url you copied earlier>

Make a branch for changes you're makeing git checkout -b branch-name

Make necessary changes

Commit your changes git commit

Push your changes to your fork on GitHub git push origin branch-name

Go to your fork on GitHub to see a Compare and pull request button

Click on it and give necessary details

Title: How to do a GitHub pull request


问:
Command to run heroku run rake db:migrate on production db when you also have a staging db in heroku
I have a ruby on rails app, leveraging Postgres running in heroku. I have a staging environment and a production environment in heroku. I want to run the heroku run rake db:migrate on the production environment however I can find the command to do so, any help would be greatly appreciated</p>

答:
I think you can just set the remote to get it to pick the right environment:</p>

```<code>heroku run rake db:migrate --remote production
</code>```

Body:
I think you can just set the remote to get it to pick the right environment:

heroku run rake db:migrate --remote production


问:
xdotool not working inside a shell script
I am trying to make the wallpaper changing process easier in AwesomeWM with a script which reads a path to an image and replaces the existing wallpaper with the path I gave; and then restart the WM.

My code looks like:

```<code>#!/bin/bash

if [[ $1 != "" ]] && [ -f $1 ]; then
        cp $1 /usr/local/share/awesome/themes/modded/background.png
        xdotool key super+ctrl+r
else
        echo 'Invalid file!'
fi
</code>```

Unfortunately, xdotool won't work and I don't know why, because if I issue it from a terminal (outside of a script), it will restart my window manager perfectly (super+ctrl+r restarts AwesomeWM).

I know it would be better to use awesome.restart function from rc.lua, but I don't know how to implement or include this code inside my shell script.

答: You don't have to restart awesome. You can use awesome-client to call a function inside awesome to load the wallpaper.

Body:
I am trying to make the wallpaper changing process easier in AwesomeWM with a script which reads a path to an image and replaces the existing wallpaper with the path I gave; and then restart the WM.

My code looks like:

#!/bin/bash

if [[ $1 != "" ]] && [ -f $1 ]; then
        cp $1 /usr/local/share/awesome/themes/modded/background.png
        xdotool key super+ctrl+r
else
        echo 'Invalid file!'
fi

Unfortunately, xdotool won't work and I don't know why, because if I issue it from a terminal (outside of a script), it will restart my window manager perfectly (super+ctrl+r restarts AwesomeWM).

I know it would be better to use awesome.restart function from rc.lua, but I don't know how to implement or include this code inside my shell script.


问:
C#: Is it necessary to dispose of a graphics element inside a custom control?
I've created a custom control, overridden it's paint event. When I try to dispose of the graphics I create they just disappear from the screen. Don't I need to use dispose in custom controls?

EDIT: I've included a code snippet. Why can't i dispose the dc graphics object, created from the PaintEventArgs? Do i need to dispose it?

```<code>class canvas : Control
    {

        PointF mouseDown;

        float newX;
        float newY;
        float zoomFactor = 1F;

        Graphics _dc;

        public canvas()
        {
            this.DoubleBuffered = true;
            mouseDown = new PointF(0F, 0F);
            this.Paint += new PaintEventHandler(ctrl_Paint);
        }

        private void ctrl_Paint(object sender, PaintEventArgs e)
        {

            Graphics dc = e.Graphics;
            _dc = dc;

            dc.SmoothingMode = SmoothingMode.AntiAlias;

            Color gridColor = Color.FromArgb(230, 230, 230);
            Pen gridPen = new Pen(gridColor, 1);

            float offX = (float)((Math.Sqrt(Math.Pow(newX, 2)) % (30 * zoomFactor)));
            float offY = (float)((Math.Sqrt(Math.Pow(newY, 2)) % (30 * zoomFactor)));

            for (float y = offY; y < this.Height; y = y + 30 * zoomFactor)
            {
                dc.DrawLine(gridPen, 0, y, this.Width, y);
            }
            for (float x = offX; x < this.Width; x = x + 30 * zoomFactor)
            {
                dc.DrawLine(gridPen, x, 0, x, this.Height);
            }

            dc.TranslateTransform(newX, newY);
            dc.ScaleTransform(zoomFactor, zoomFactor, MatrixOrder.Prepend);

            float XPosition = 10;
            float YPosition = 10;
            float CornerRadius = 5;
            float Width = 50;
            float Height = 50;

            Color BoxColor = Color.FromArgb(0, 0, 0);
            Pen BoxPen = new Pen(BoxColor, 2);

            GraphicsPath Path = new GraphicsPath();

            Path.AddLine(XPosition + CornerRadius, YPosition, XPosition + Width - (CornerRadius * 2), YPosition);
            Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition, CornerRadius * 2, CornerRadius * 2, 270, 90);
            Path.AddLine(XPosition + Width, YPosition + CornerRadius, XPosition + Width, YPosition + Height - (CornerRadius * 2));
            Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 0, 90);
            Path.AddLine(XPosition + Width - (CornerRadius * 2), YPosition + Height, XPosition + CornerRadius, YPosition + Height);
            Path.AddArc(XPosition, YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 90, 90);
            Path.AddLine(XPosition, YPosition + Height - (CornerRadius * 2), XPosition, YPosition + CornerRadius);
            Path.AddArc(XPosition, YPosition, CornerRadius * 2, CornerRadius * 2, 180, 90);

            Path.CloseFigure();

            dc.DrawPath(BoxPen, Path);

            LinearGradientBrush lgb = new LinearGradientBrush(new PointF(XPosition + (Width / 2), YPosition), new PointF(XPosition + (Width / 2), YPosition + Height), Color.RosyBrown, Color.Red);

            dc.FillPath(lgb, Path);

        }
}
</code>```

答:
Without an example it's hard to say exactly where the phoblem is, but I can guess:

In your overriden OnPaint event, there's a parameter PaintEventArgs. You should perform all drawing onto this parameter's Graphics object, and you're good to go. That should make your graphics stick.

Body:
I've created a custom control, overridden it's paint event. When I try to dispose of the graphics I create they just disappear from the screen. Don't I need to use dispose in custom controls?

EDIT: I've included a code snippet. Why can't i dispose the dc graphics object, created from the PaintEventArgs? Do i need to dispose it?

class canvas : Control
    {

        PointF mouseDown;

        float newX;
        float newY;
        float zoomFactor = 1F;

        Graphics _dc;

        public canvas()
        {
            this.DoubleBuffered = true;
            mouseDown = new PointF(0F, 0F);
            this.Paint += new PaintEventHandler(ctrl_Paint);
        }

        private void ctrl_Paint(object sender, PaintEventArgs e)
        {

            Graphics dc = e.Graphics;
            _dc = dc;

            dc.SmoothingMode = SmoothingMode.AntiAlias;

            Color gridColor = Color.FromArgb(230, 230, 230);
            Pen gridPen = new Pen(gridColor, 1);

            float offX = (float)((Math.Sqrt(Math.Pow(newX, 2)) % (30 * zoomFactor)));
            float offY = (float)((Math.Sqrt(Math.Pow(newY, 2)) % (30 * zoomFactor)));

            for (float y = offY; y < this.Height; y = y + 30 * zoomFactor)
            {
                dc.DrawLine(gridPen, 0, y, this.Width, y);
            }
            for (float x = offX; x < this.Width; x = x + 30 * zoomFactor)
            {
                dc.DrawLine(gridPen, x, 0, x, this.Height);
            }

            dc.TranslateTransform(newX, newY);
            dc.ScaleTransform(zoomFactor, zoomFactor, MatrixOrder.Prepend);

            float XPosition = 10;
            float YPosition = 10;
            float CornerRadius = 5;
            float Width = 50;
            float Height = 50;

            Color BoxColor = Color.FromArgb(0, 0, 0);
            Pen BoxPen = new Pen(BoxColor, 2);

            GraphicsPath Path = new GraphicsPath();

            Path.AddLine(XPosition + CornerRadius, YPosition, XPosition + Width - (CornerRadius * 2), YPosition);
            Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition, CornerRadius * 2, CornerRadius * 2, 270, 90);
            Path.AddLine(XPosition + Width, YPosition + CornerRadius, XPosition + Width, YPosition + Height - (CornerRadius * 2));
            Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 0, 90);
            Path.AddLine(XPosition + Width - (CornerRadius * 2), YPosition + Height, XPosition + CornerRadius, YPosition + Height);
            Path.AddArc(XPosition, YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 90, 90);
            Path.AddLine(XPosition, YPosition + Height - (CornerRadius * 2), XPosition, YPosition + CornerRadius);
            Path.AddArc(XPosition, YPosition, CornerRadius * 2, CornerRadius * 2, 180, 90);

            Path.CloseFigure();

            dc.DrawPath(BoxPen, Path);

            LinearGradientBrush lgb = new LinearGradientBrush(new PointF(XPosition + (Width / 2), YPosition), new PointF(XPosition + (Width / 2), YPosition + Height), Color.RosyBrown, Color.Red);

            dc.FillPath(lgb, Path);

        }
}

ContentLicense: CC BY-SA 2.5


问:
CSS3: Nested flexbox form messes up spacing
I am trying to make a flexbox form with label and input on the same line. Using flex-basis and and other flex properties gives the expected and desired result.

However, if one has to nest that flexbox inside another element with a set width, the whole thing falls apart.

E.g. see the attached fiddle and run it with and without the div {width:30%}

How can I get around this?

fiddle

答:
You can add width:100%;  to form div

https://jsfiddle.net/fjqjrs9j/1/


问:
Inject Jar and replace classes in running JVM
I want to be able to replace and add some classes to an already running JVM. I read that I need to use CreateRemoteThread, but I don't completely get it. I read this post on how to do it (Software RnD), but I can't figure out what it does and why. Besides that, it only introduces new classes, but doesn't change existing ones. How can I do it with C++?

答:
You don't even need CreateRemoteThread - there is an official way to connect to remote JVM and replace loaded classes by using Attach API.

You need a Java Agent that calls Instrumentation.redefineClasses.

```<code>public static void agentmain(String args, Instrumentation instr) throws Exception {
    Class oldClass = Class.forName("org.pkg.MyClass");
    Path newFile = Paths.get("/path/to/MyClass.class");
    byte[] newData = Files.readAllBytes(newFile);

    instr.redefineClasses(new ClassDefinition(oldClass, newData));
}
</code>```

You'll have to add MANIFEST.MF with Agent-Class attribute and pack the agent into a jar file.

Then use Dynamic Attach to inject the agent jar into the running VM (with process ID = pid).

```<code>import com.sun.tools.attach.VirtualMachine;
...

    VirtualMachine vm = VirtualMachine.attach(pid);
    try {
        vm.loadAgent(agentJarPath, options);
    } finally {
        vm.detach();
    }
</code>```

A bit more details in the article.

If you insist on using C/C++ instead of Java API, you may look at my jattach utility.

Body:
You don't even need CreateRemoteThread - there is an official way to connect to remote JVM and replace loaded classes by using Attach API.

You need a Java Agent that calls Instrumentation.redefineClasses.

public static void agentmain(String args, Instrumentation instr) throws Exception {
    Class oldClass = Class.forName("org.pkg.MyClass");
    Path newFile = Paths.get("/path/to/MyClass.class");
    byte[] newData = Files.readAllBytes(newFile);

    instr.redefineClasses(new ClassDefinition(oldClass, newData));
}

You'll have to add MANIFEST.MF with Agent-Class attribute and pack the agent into a jar file.

Then use Dynamic Attach to inject the agent jar into the running VM (with process ID = pid).

import com.sun.tools.attach.VirtualMachine;
...

    VirtualMachine vm = VirtualMachine.attach(pid);
    try {
        vm.loadAgent(agentJarPath, options);
    } finally {
        vm.detach();
    }

A bit more details in the article.

If you insist on using C/C++ instead of Java API, you may look at my jattach utility.


问:
How to translate this matlab code to python(numpy)
Matlab code :

```<code> Sol(indx,j) = mf* ((alpha/dx^2)*(Sol(indx+1,j-1)-2*Sol(indx,j-1)+Sol(indx-1,j-1))...
        + (K/dt)*Sol(indx,j-1) +(1/dt^2)*(2*Sol(indx,j-1) - Sol(indx,j-2)));
</code>```

The code I translate :

```<code> Sol[indx,j] = mf* ((alpha/(dx**2))*(Sol[indx+1,j-1]-2*Sol[indx,j-1]+Sol[indx-1,j-1])+ (K/dt)*Sol[indx,j-1] +(1/(dt**2))*(2*Sol[indx,j-1] - Sol[indx,j-2]))
</code>```

I do not think I translate it correctly because the result does not match

Could someone help me? Thanks

edit:
I really want to give some test value, but the matrix is about 200*200. I do not think copying/pastng those values is a good idea. And I cannot give you guys the full code because it is an homework question.

答:
If you're using Python 2.7 (?) then division returns the floor value. You can return true division values by importing 'division':

e.g.

```<code>1/2
>>0

from __future__ import division
1/2
>>0.5
</code>```

Python3+ does true division right out of the box though.

Body:
Matlab code :

 Sol(indx,j) = mf* ((alpha/dx^2)*(Sol(indx+1,j-1)-2*Sol(indx,j-1)+Sol(indx-1,j-1))...
        + (K/dt)*Sol(indx,j-1) +(1/dt^2)*(2*Sol(indx,j-1) - Sol(indx,j-2)));

The code I translate :

 Sol[indx,j] = mf* ((alpha/(dx**2))*(Sol[indx+1,j-1]-2*Sol[indx,j-1]+Sol[indx-1,j-1])+ (K/dt)*Sol[indx,j-1] +(1/(dt**2))*(2*Sol[indx,j-1] - Sol[indx,j-2]))

I do not think I translate it correctly because the result does not match

Could someone help me? Thanks

edit:
I really want to give some test value, but the matrix is about 200*200. I do not think copying/pastng those values is a good idea. And I cannot give you guys the full code because it is an homework question.

Body:
If you're using Python 2.7 (?) then division returns the floor value. You can return true division values by importing 'division':

e.g.

1/2
>>0

from __future__ import division
1/2
>>0.5

Python3+ does true division right out of the box though.