问:
How to create a very long level selection scene?
I am in the process of creating a level selection scene for my first game. After looking here and there on the internet I realized that level selection is just another scene of game (Correct me if I am wrong).

My Game is going to have 1000+ levels. So my level select scene is going to be very long (vertical). And I think loading this long scene will be slow (have planned to use several animations and images).

Further, I have observed that some games like TwoDots and “Angry birds Action”, do not load all levels and instead, load current Plus 20 or 30 levels, and current minus 20 or 30 levels. And when we scroll up, it loads new levels and unload previous levels.

In the following image, I am scrolling to my previous levels and after showing 30 previous levels, it goes to a small loading at bottom (see below image at bottom there is a loading bar, and it will load previous 30 levels and unload top 30), and then loads more levels:

What should be done to achieve this?

答:
You could use more than one scene for your level and then load those once player wants to see them via SceneManager.LoadSceneAsync("SceneName", LoadSceneMode.Additive). Other than that it is important to get your scrolling performant. Scroll view will create a lot of redrawing, you might need to actually move the camera in order to create little overhead. When using a scroll view, make sure to use a rectMask2D instead of a mask in order to easy cull everything that is not in the players view (will create less draw calls).

Also consider to activate and deactivate game objects or to even have a pool of game objects that can represent your map. With object pooling you would make sure to not create any garbage.


来源: stackexchange

问:
convert list of lists with time strings to seconds and find count times between
I have a list of lists with time strings in them (this format "17:04:20"). I want to iterate through the list and count the times with a gap of 5 minutes or greater.

```<code>Eg. [[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]]
</code>```

In this case the gap would be from 17:08:54 + 5 minutes until 17:50:33.

I've been trying to do this by replacing the : in  the time strings and then turning the value into seconds and putting them sorted into a list of lists. Then I wanted to go through the list and if the next value is more than 300 seconds record this value.

Im having trouble even changing the strings to second can anyone help ?

答:
You can get difference count using this code. Just pass your list to this function.

```<code>import datetime
def countDifference(date_list):
    final_count = []
    for inner_dt in date_list:
        count = 0
        new_list = []

        for dt_elem in inner_dt:
            new_date = datetime.datetime.strptime(dt_elem, "%H:%M:%S")
            total_seconds = new_date.hour*60*60 + new_date.minute*60 + new_date.second
            new_list.append(total_seconds)
        new_list.sort()

        for first, second in zip(new_list, new_list[1:]):
            if second - first >= 300: count+=1
        final_count.append((inner_dt, count))

    return final_count

print countDifference([[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]])
</code>```

Output:

```<code>[([], 0), ([], 0), (['17:03:22', '17:08:54', '17:50:33', '17:55:20'], 2), ([], 0)]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a list of lists with time strings in them (this format "17:04:20"). I want to iterate through the list and count the times with a gap of 5 minutes or greater.

Eg. [[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]]

In this case the gap would be from 17:08:54 + 5 minutes until 17:50:33.

I've been trying to do this by replacing the : in  the time strings and then turning the value into seconds and putting them sorted into a list of lists. Then I wanted to go through the list and if the next value is more than 300 seconds record this value.

Im having trouble even changing the strings to second can anyone help ?

Body:
You can get difference count using this code. Just pass your list to this function.

import datetime
def countDifference(date_list):
    final_count = []
    for inner_dt in date_list:
        count = 0
        new_list = []

        for dt_elem in inner_dt:
            new_date = datetime.datetime.strptime(dt_elem, "%H:%M:%S")
            total_seconds = new_date.hour*60*60 + new_date.minute*60 + new_date.second
            new_list.append(total_seconds)
        new_list.sort()

        for first, second in zip(new_list, new_list[1:]):
            if second - first >= 300: count+=1
        final_count.append((inner_dt, count))

    return final_count

print countDifference([[],[],["17:03:22","17:08:54","17:50:33","17:55:20"],[]])

Output:

[([], 0), ([], 0), (['17:03:22', '17:08:54', '17:50:33', '17:55:20'], 2), ([], 0)]


问:
WPF Avalondock save layout to next start-up
I am using Avalondock tool and I think it is a great tool of using. It includes a lot of good features and easy to use.

I have used Avalondock a lot and i have implemented in my whole application, but one thing that would be insane to have is to remember the layout to next startup.

I have a userconfig that saves other configuration of the application, so i know how that work, but I need to know in details how to save and load the layout of floated panels.

I have read some other posts that I thought I could figure it out, but it became too hard, unfortunately.

I hope some sweet soul could give me an explanation about how this works and what I have to do step by step!

Good day

Best regard
Tobias

答:
You should be able to serialize the layout using

XmlLayoutSerializer

in

Xceed.Wpf.AvalonDock.Layout.Serialization


问:
redux-saga Network Error - OPTIONS request
I've create a wizard form that I change a little bit. Each step of the form fetch some data from API when componentWillMount and when user click on "next" to go to the next form part, I call dispatch another action with componentWillUnmout to dispatch an Update (PUT) action from the API.

I'm using redux-saga with react.

Here is the saga.js file :

```<code>import { call, put, takeEvery } from 'redux-saga/effects';
import accountApi from '../../api/account';
import * as actions from '../../actions';

import {
    FETCH_ACCOUNT_REQUEST,
    FETCH_ACCOUNT_SUCCESS,
    UPDATE_ACCOUNT_REQUEST,
    UPDATE_ACCOUNT_SUCCESS
} from '../../actions/types';

export function* fetchAccount(action) {
    const account = yield call(accountApi.fetchAccount, action.params);
    yield put({ type: FETCH_ACCOUNT_SUCCESS, account: account });
}

export function* updateAccount(action) {
    const accountUpdated = yield call(accountApi.updateAccount, action.params, action.accountUpdated);
    yield put({ type: UPDATE_ACCOUNT_SUCCESS, accountUpdated: accountUpdated });
}

export function* accountListener() {
    yield takeEvery(FETCH_ACCOUNT_REQUEST, fetchAccount);
    yield takeEvery(UPDATE_ACCOUNT_REQUEST, updateAccount);
}
</code>```

There is the API file :

```<code>import axios from 'axios';

const baseUrl = '<link>';

const accountApi = {
    fetchAccount(params) {
        return axios.get(`${baseUrl}${params}`)
            .then(response => {
                return response.data
            })
    },

    updateAccount(params, accountUpdated) {
        return axios.put(`${baseUrl}${params}`, accountUpdated)
            .then(response => {
                return response.data
            })
    }
}

export default accountApi;
</code>```

the action :

```<code>import axios from 'axios';

import {
    FETCH_ACCOUNT_REQUEST,
    UPDATE_ACCOUNT_REQUEST
} from './types';

export function fetchAccount(params) {
    return {
        type: FETCH_ACCOUNT_REQUEST,
        params
    }
}

export function updateAccount(params, accountUpdated) {
    return {
        type: UPDATE_ACCOUNT_REQUEST,
        params,
        accountUpdated
    }
}
</code>```

the reducer :

```<code>import {
    FETCH_ACCOUNT_REQUEST,
    FETCH_ACCOUNT_SUCCESS,
    UPDATE_ACCOUNT_REQUEST,
    UPDATE_ACCOUNT_SUCCESS
} from '../actions/types';

export default function(state = null, action) {
    switch (action.type) {
        case FETCH_ACCOUNT_REQUEST:
            return null;
        case FETCH_ACCOUNT_SUCCESS:
            return action.account;
        case UPDATE_ACCOUNT_REQUEST:
            return null;
        case UPDATE_ACCOUNT_SUCCESS:
            return action.accountUpdated;
        default:
            return state;
    }
}
</code>```

And the component :

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Field, reduxForm } from 'redux-form';
import * as actions from '../../actions';
import validate from './validate';

class FormGlobalInformations extends Component {
    componentWillMount() {
        const fakeAccountId = '?accountId=0012400000oAMhY';
        this.props.actions.fetchAccount(fakeAccountId);
    }

    componentDidMount() {
        if (this.props.account) {
            this.props.initialize({
                companyName: this.props.account.companyName,
                typologie: this.props.account.typologie,
                phone: this.props.account.phone
            });
        }
    }

    componentWillUnmount() {
        const fakeAccountId = '?accountId=0012400000oAMhY';
        this.props.actions.updateAccount(fakeAccountId, this.props.form.Information.values);
    }

    render() {
        const { handleSubmit } = this.props;
        return (
            <form onSubmit={handleSubmit}>
                    <Field
                        label="Nom de l'établissement"
                        name="companyName"
                        type="text"
                        className="form-group"
                        component={this.renderFields}
                    />
                    <Field
                        label="Type d'établissement : "
                        name="typologie"
                        component={this.renderSelect}
                        className="form-group"
                    />
                    <Field
                        label="Votre numéro de téléphone de contact"
                        name="phone"
                        type="number"
                        className="form-group"
                        component={this.renderFields}
                    />
                    <button type="submit" className="btn btn-tiller-full btn-tiller-right">Suite</button>
            </form>
        );
    }
}

function mapStateToProps(state) {
    return {
        account: state.account,
        form: state.form
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(actions, dispatch)
    }
}

FormGlobalInformations = connect(mapStateToProps, mapDispatchToProps)(FormGlobalInformations);

FormGlobalInformations = reduxForm({
    form: 'Information',
    destroyOnUnmount: false,
    validate
})(FormGlobalInformations);

export default FormGlobalInformations;
</code>```

(The next form step component is the same so I fetch data onmount and I update on unmount).

Here is the index.js file :

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { createStore, applyMiddleware } from 'redux';
import logger from 'redux-logger';
// import ReduxThunk from 'redux-thunk';
import { all } from 'redux-saga/effects';

import createSagaMiddleware from 'redux-saga';
import reducers from './reducers';

// Components
import Informations from './components/Informations/Informations';
import Navigation from './components/Navigation/Navigation';
import Header from './components/Navigation/Header';

import { accountListener } from './services/account/saga';

function* RootListener() {
    yield all([
        accountListener()
    ]);
}

const sagaMiddleware = createSagaMiddleware();
const store = createStore(
    reducers,
    applyMiddleware(sagaMiddleware)
);

sagaMiddleware.run(RootListener);

ReactDOM.render(
    <Provider store={store}>
        <BrowserRouter>
            <div>
                <Header />
                <Navigation />
                <Switch>
                    <Route path="/informations" component={Informations} />
                </Switch>
            </div>
        </BrowserRouter>
    </Provider>,
    document.querySelector('.container-fluid')
);
</code>```

Here is the error that I have when I try to update :

And I have a OPTIONS request...

Someone could help ?

答:
Update (PUT) action from the API.

And I have a OPTIONS request...

Most likely that issue is not dependent on redux-saga, because error occurs in axios call inside. Supposed preconditions with PUT verb affects mandatory OPTIONS preflight query, which returns available CORS politics for request origin. It's mandatory because of PUT is state-changing verb, so returning allowance HTTP header, like in GET-requests, is very late, that's why independent preflight query is used.

Read more here How to apply CORS preflight cache to an entire domain and here Why is an OPTIONS request sent and can I disable it?

Simplest solution without preflight query provided here: https://stackoverflow.com/a/40373949/7878274

Body:
I've create a wizard form that I change a little bit. Each step of the form fetch some data from API when componentWillMount and when user click on "next" to go to the next form part, I call dispatch another action with componentWillUnmout to dispatch an Update (PUT) action from the API.

I'm using redux-saga with react.

Here is the saga.js file :

import { call, put, takeEvery } from 'redux-saga/effects';
import accountApi from '../../api/account';
import * as actions from '../../actions';

import {
    FETCH_ACCOUNT_REQUEST,
    FETCH_ACCOUNT_SUCCESS,
    UPDATE_ACCOUNT_REQUEST,
    UPDATE_ACCOUNT_SUCCESS
} from '../../actions/types';

export function* fetchAccount(action) {
    const account = yield call(accountApi.fetchAccount, action.params);
    yield put({ type: FETCH_ACCOUNT_SUCCESS, account: account });
}

export function* updateAccount(action) {
    const accountUpdated = yield call(accountApi.updateAccount, action.params, action.accountUpdated);
    yield put({ type: UPDATE_ACCOUNT_SUCCESS, accountUpdated: accountUpdated });
}

export function* accountListener() {
    yield takeEvery(FETCH_ACCOUNT_REQUEST, fetchAccount);
    yield takeEvery(UPDATE_ACCOUNT_REQUEST, updateAccount);
}

There is the API file :

import axios from 'axios';

const baseUrl = '<link>';

const accountApi = {
    fetchAccount(params) {
        return axios.get(`${baseUrl}${params}`)
            .then(response => {
                return response.data
            })
    },

    updateAccount(params, accountUpdated) {
        return axios.put(`${baseUrl}${params}`, accountUpdated)
            .then(response => {
                return response.data
            })
    }
}

export default accountApi;

the action :

import axios from 'axios';

import {
    FETCH_ACCOUNT_REQUEST,
    UPDATE_ACCOUNT_REQUEST
} from './types';

export function fetchAccount(params) {
    return {
        type: FETCH_ACCOUNT_REQUEST,
        params
    }
}

export function updateAccount(params, accountUpdated) {
    return {
        type: UPDATE_ACCOUNT_REQUEST,
        params,
        accountUpdated
    }
}

the reducer :

import {
    FETCH_ACCOUNT_REQUEST,
    FETCH_ACCOUNT_SUCCESS,
    UPDATE_ACCOUNT_REQUEST,
    UPDATE_ACCOUNT_SUCCESS
} from '../actions/types';

export default function(state = null, action) {
    switch (action.type) {
        case FETCH_ACCOUNT_REQUEST:
            return null;
        case FETCH_ACCOUNT_SUCCESS:
            return action.account;
        case UPDATE_ACCOUNT_REQUEST:
            return null;
        case UPDATE_ACCOUNT_SUCCESS:
            return action.accountUpdated;
        default:
            return state;
    }
}

And the component :

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Field, reduxForm } from 'redux-form';
import * as actions from '../../actions';
import validate from './validate';

class FormGlobalInformations extends Component {
    componentWillMount() {
        const fakeAccountId = '?accountId=0012400000oAMhY';
        this.props.actions.fetchAccount(fakeAccountId);
    }

    componentDidMount() {
        if (this.props.account) {
            this.props.initialize({
                companyName: this.props.account.companyName,
                typologie: this.props.account.typologie,
                phone: this.props.account.phone
            });
        }
    }

    componentWillUnmount() {
        const fakeAccountId = '?accountId=0012400000oAMhY';
        this.props.actions.updateAccount(fakeAccountId, this.props.form.Information.values);
    }

    render() {
        const { handleSubmit } = this.props;
        return (
            <form onSubmit={handleSubmit}>
                    <Field
                        label="Nom de l'établissement"
                        name="companyName"
                        type="text"
                        className="form-group"
                        component={this.renderFields}
                    />
                    <Field
                        label="Type d'établissement : "
                        name="typologie"
                        component={this.renderSelect}
                        className="form-group"
                    />
                    <Field
                        label="Votre numéro de téléphone de contact"
                        name="phone"
                        type="number"
                        className="form-group"
                        component={this.renderFields}
                    />
                    <button type="submit" className="btn btn-tiller-full btn-tiller-right">Suite</button>
            </form>
        );
    }
}

function mapStateToProps(state) {
    return {
        account: state.account,
        form: state.form
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(actions, dispatch)
    }
}

FormGlobalInformations = connect(mapStateToProps, mapDispatchToProps)(FormGlobalInformations);

FormGlobalInformations = reduxForm({
    form: 'Information',
    destroyOnUnmount: false,
    validate
})(FormGlobalInformations);

export default FormGlobalInformations;

(The next form step component is the same so I fetch data onmount and I update on unmount).

Here is the index.js file :

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { createStore, applyMiddleware } from 'redux';
import logger from 'redux-logger';
// import ReduxThunk from 'redux-thunk';
import { all } from 'redux-saga/effects';

import createSagaMiddleware from 'redux-saga';
import reducers from './reducers';

// Components
import Informations from './components/Informations/Informations';
import Navigation from './components/Navigation/Navigation';
import Header from './components/Navigation/Header';

import { accountListener } from './services/account/saga';

function* RootListener() {
    yield all([
        accountListener()
    ]);
}

const sagaMiddleware = createSagaMiddleware();
const store = createStore(
    reducers,
    applyMiddleware(sagaMiddleware)
);

sagaMiddleware.run(RootListener);

ReactDOM.render(
    <Provider store={store}>
        <BrowserRouter>

                <Navigation />
                <Switch>
                    <Route path="/informations" component={Informations} />
                </Switch>

        </BrowserRouter>
    </Provider>,
    document.querySelector('.container-fluid')
);

Here is the error that I have when I try to update :

And I have a OPTIONS request...

Someone could help ?


答:
Example of using 2 left joins for "from member" and "to member"</p>

```<code>select
       m.*, from_men.username, to_mem.username
from messages m
left join members as from_mem on m.from_id = from_mem.id
left join members as to_mem   on m.to_id = to_mem.id
</code>```

Title: Can Inner join be used effeciently with RIGHT or LEFT Join together in single mysql query

Body:
I am working on php-mysql script and having two tables namely messages and members. The data in these tables is given below for example:

messages table:

_________________________________________________________________
|m_id| from_id | to_id | msg_subject | msg_body     | sent_time  |
------------------------------------------------------------------
| 1  |    142  |  335  |    hello    |  how are you | 2017-25-10 |
------------------------------------------------------------------
| 2  |    225  |  443  |    hi       |  whats up..  | 2017-26-10 |
------------------------------------------------------------------
| 3  |    332  |  110  |    urgent   |  call me now | 2017-27-10 |
------------------------------------------------------------------

and members table:

______________________________________________________________
| id   | username | f_name  |  l_name   |   city    | gender  |
---------------------------------------------------------------
| 110  |    joe   |  Joe    |    Tom    |  Rome     |    M    |
---------------------------------------------------------------
| 142  |    alb_p |  Albert |    Paul   |  Milan    |    M    |
---------------------------------------------------------------
| 225  |    ruby  |  Ruby   |    Hinge  |  Paris    |    F    |
---------------------------------------------------------------
| 332  |    ram   |  Ram    |    Sharma |  Delhi    |    M    |
---------------------------------------------------------------
| 335  |   kris   |  Kity   |    Krin   |  Milan    |    F    |
---------------------------------------------------------------
| 443  |    reema |  Reema  |    Pink   |  Dubai    |    F    |
---------------------------------------------------------------

Now I want these tables are joined in mysql query in such a way (or use two select in mysql) so that i should get the username, f_name, l_name, city and gender data of for every from_id and to_id. And also I should also get msg_subject,msg_body and sent_time. I am getting this with use of another mysql query in while loop, which I dont want to use because of performance issue for more than 500 rows. Finally I want display the following type of output using html in the web browser:

_____________________________________________________________________________
|m_id|  Message       |   Message      | Message  |   Message    | Msg Sent |
|    | From Member    |   To Member    | Subject  |   Details    |  On Date |
-----------------------------------------------------------------------------
|    |ID: 142         | ID: 335        |          |              |          |
|    |UserName: alb_p | UserName: kris |          |              |          |
|    |1st Name:Albert | 1st Name: Kity |          |              |          |
| 1  |Last Name: Paul | Last Name: Krin|  hello   | how are you  |2017-25-10|
|    |City: Milan     | City: Milan    |          |              |          |
|    |Gender: Male    | Gender: Female |          |              |          |
-----------------------------------------------------------------------------
|    |ID: 225         | ID: 443        |          |              |          |
|    |UserName: ruby  | UserName:reema |          |              |          |
|    |1st Name:Ruby   | 1st Name:Reema |          |              |          |
| 2  |Last Name:Hinge | Last Name:Pink |  hi      | Whats up..   |2017-26-10|
|    |City: Paris     | City: Dubai    |          |              |          |
|    |Gender: Female  | Gender: Female |          |              |          |
-----------------------------------------------------------------------------

and so on... for m_id row no. 3 also..

I am getting this html table style output as shown above using another mysql query in while loop but i want to achieve this in a single mysql query using double select or two joins. Please suggest me the way and give me that mysql query details.... thanks in advance.. (also to disclose I am just a starter in php-mysql programming..)

Body:
Example of using 2 left joins for "from member" and "to member"

select
       m.*, from_men.username, to_mem.username
from messages m
left join members as from_mem on m.from_id = from_mem.id
left join members as to_mem   on m.to_id = to_mem.id


问:
How do you change the background color of the empty tab space in vim?
In vim, when you create a new tab, the tab bar appears at the top of the screen.  On the left are all your tabs, on the far right is an "X" for closing the tabs.  In between, there is "empty" space, that on my screen appears white.

I'll admit, I'm very picky about how my terminal looks, and this bright white bar at the top of the screen is distracting.  Is it possible to change this color to black, or maybe even gray?

答:
Try the following: (you can put that in your .vimrc)

```<code>:hi TabLineFill ctermbg=100
</code>```

you can play with the colors and choose one that you like.

ContentLicense: CC BY-SA 2.5

Body:
Try the following: (you can put that in your .vimrc)

:hi TabLineFill ctermbg=100

you can play with the colors and choose one that you like.


问:
Is it possible to store functions in a dictionary?
I have a message coming into my C# app which is an object serialized as JSON, when i de-serialize it I have a "Name" string and a "Payload" string[], I want to be able to take the "Name" and look it up in a function dictionary, using the "Payload" array as its parameters and then take the output to return to the client sending the message, is this possible in C#?

I've found a stack overflow answer here where the second part seems plausible but i don't know what I'm referencing with State

答:
My solution with input parameters, and a int as Key of Invoke:

```<code>  private static Dictionary<int, Action> MethodDictionary(string param1, string param2, int param3) => new Dictionary<int, Action>
    {
            {1 , () =>   Method1(param1, param2, param3) },
            {2 , () =>   Method2(param1, param2, param3) },
            {3 , () =>   Method3(param1, param2, param3) },
            {4 , () =>   Method4(param1, param2, param3) },
            {5 , () =>   Method5(param1, param2, param3) }
    };
</code>```

And to invoke a method:

```<code> var methodDictionary = MethodDictionary("param1", "param2", 1);
 methodDictionary[2].Invoke();
</code>```

This will execute Method2.

Hope it helps!

Body:
My solution with input parameters, and a int as Key of Invoke:

  private static Dictionary<int, Action> MethodDictionary(string param1, string param2, int param3) => new Dictionary<int, Action>
    {
            {1 , () =>   Method1(param1, param2, param3) },
            {2 , () =>   Method2(param1, param2, param3) },
            {3 , () =>   Method3(param1, param2, param3) },
            {4 , () =>   Method4(param1, param2, param3) },
            {5 , () =>   Method5(param1, param2, param3) }
    };

And to invoke a method:

 var methodDictionary = MethodDictionary("param1", "param2", 1);
 methodDictionary[2].Invoke();

This will execute Method2.

Hope it helps!


问:
Parsing XML using Python ElementTree
I have an XML document in the following format

```<code><root>
<H D="14/11/2017">
<FC>
    <F LV="0">The quick</F>
    <F LV="1">brown</F>
    <F LV="2">fox</F>
</FC>
</H>
<H D="14/11/2017">
<FC>
    <F LV="0">The lazy</F>
    <F LV="1">fox</F>
</FC>
</H>
</root>
</code>```

How can I extract the text from 'D' inside H tag and also all the text inside the F tags.

答:
From ElementTree docs:

We can import this data by reading from a file:

```<code>import xml.etree.ElementTree as ET

tree = ET.parse('country_data.xml')
root = tree.getroot()
</code>```

Or directly from a string:

```<code>root = ET.fromstring(country_data_as_string)
</code>```

and later in the same page, 20.5.1.4. Finding interesting elements:

```<code>for neighbor in root.iter('neighbor'):
    print(neighbor.attrib)
</code>```

Which translate to:

```<code>import xml.etree.ElementTree as ET

root = ET.fromstring("""
<root>
<H D="14/11/2017">
<FC>
    <F LV="0">The quick</F>
    <F LV="1">brown</F>
    <F LV="2">fox</F>
</FC>
</H>
<H D="14/11/2017">
<FC>
    <F LV="0">The lazy</F>
    <F LV="1">fox</F>
</FC>
</H>
</root>""")
# root = tree.getroot()
for h in root.iter("H"):
    print (h.attrib["D"])
for f in root.iter("F"):
    print (f.attrib, f.text)
</code>```

output:

```<code>14/11/2017
14/11/2017
{'LV': '0'} The quick
{'LV': '1'} brown
{'LV': '2'} fox
{'LV': '0'} The lazy
{'LV': '1'} fox
</code>```

Title: Parsing XML using Python ElementTree

Body:
I have an XML document in the following format

<root>
<H D="14/11/2017">
<FC>
    <F LV="0">The quick</F>
    <F LV="1">brown</F>
    <F LV="2">fox</F>
</FC>
</H>
<H D="14/11/2017">
<FC>
    <F LV="0">The lazy</F>
    <F LV="1">fox</F>
</FC>
</H>
</root>

How can I extract the text from 'D' inside H tag and also all the text inside the F tags.

Body:
From ElementTree docs:

We can import this data by reading from a file:

import xml.etree.ElementTree as ET

tree = ET.parse('country_data.xml')
root = tree.getroot()

Or directly from a string:

root = ET.fromstring(country_data_as_string)

and later in the same page, 20.5.1.4. Finding interesting elements:

for neighbor in root.iter('neighbor'):
    print(neighbor.attrib)

Which translate to:

import xml.etree.ElementTree as ET

root = ET.fromstring("""
<root>
<H D="14/11/2017">
<FC>
    <F LV="0">The quick</F>
    <F LV="1">brown</F>
    <F LV="2">fox</F>
</FC>
</H>
<H D="14/11/2017">
<FC>
    <F LV="0">The lazy</F>
    <F LV="1">fox</F>
</FC>
</H>
</root>""")
# root = tree.getroot()
for h in root.iter("H"):
    print (h.attrib["D"])
for f in root.iter("F"):
    print (f.attrib, f.text)

output:

14/11/2017
14/11/2017
{'LV': '0'} The quick
{'LV': '1'} brown
{'LV': '2'} fox
{'LV': '0'} The lazy
{'LV': '1'} fox


问:
Progressbar in concurrent request
I am making multiple concurrent requests on my server & it's working fine.

But I want to show the total progress of all request.

How can I achieve this?

My Logic

```<code>for i in 0..5 {

   POST Request1

   MultipartformData request2

}
</code>```

答:
If you are using libraries such as Alamofire or AFNetworking they provide you an NSProgress object.

The cool fact about NSProgressis that you can build a sort of hierarchy that keeps a global progress while you are adding child tasks.

For further information check these resources:

Apple doc

Tutorial by Ole Begeman

Tutorial by ToughBot

Title: Progressbar in concurrent request

Body:
I am making multiple concurrent requests on my server & it's working fine.

But I want to show the total progress of all request.

How can I achieve this?

My Logic

for i in 0..5 {

   POST Request1

   MultipartformData request2

}


问:
How to pass argument for function in controller from view
I have function in controller with one argument and now I want to pass value for it from view through url.

courses.php

```<code>public function index($id){
   print_r();
   exit;
}
</code>```

coursesview.php

```<code><a class="jscroll-next" href="<?php echo base_url(); ?>/courses/index?page=<?php echo $nextPage; ?>&id=<?php echo $parentId ?>">next page</a>
</code>```

How it possible?

答:
From the user guide,
Simply put the parameter in an array and pass it to the view by using the second parameter of load->view().

Afterwards, in the view, the variable will be available as the key.
In this example: $id or $anothervar.

courses.php

```<code>public function index($id){
  $data = array('id' => $id, 'anothervar' => 'yeahi');
  $this->load->view('coursesview', $data);
  // exit;
}
</code>```

coursesview.php

```<code>echo $id; // the ID
echo $anothervar; // "yeahi"
</code>```

Body:
I have function in controller with one argument and now I want to pass value for it from view through url.

courses.php

public function index($id){
   print_r();
   exit;
}

coursesview.php

<a class="jscroll-next" href="<?php echo base_url(); ?>/courses/index?page=<?php echo $nextPage; ?>&id=<?php echo $parentId ?>">next page

How it possible?

Body:
From the user guide,
Simply put the parameter in an array and pass it to the view by using the second parameter of load->view().

Afterwards, in the view, the variable will be available as the key.
In this example: $id or $anothervar.

courses.php

public function index($id){
  $data = array('id' => $id, 'anothervar' => 'yeahi');
  $this->load->view('coursesview', $data);
  // exit;
}

coursesview.php

echo $id; // the ID
echo $anothervar; // "yeahi"


问:
Is there a way to make inline-block elements behave like table cells?
I am trying to mimic an HTML table with css classes, but the last "cell" element always gets pushed to the next line.

The way I am currently getting around this is to decrease the width of the last element by a few percent, so that the total width of the elements adds up to ~ 97%. This protects the last element from being pushed to the next line, but it doesn't look as nice because there's unused space at the end.

Is there a way to get the table cells to line up nicely and use 100% of the containing width?

.cell {
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="table" style="width: 100%">
  <div class="row" style="width: 100%">
    <div class="cell" style="width:40%">Last Name</div>
    <div class="cell" style="width:40%">First Name</div>
    <div class="cell" style="width:20%">Age</div>
  </div>
</div></code>```

答:
This is a well known "problem" with display:inline-block;

One solution is to comment the "space" between your divs.
Other solutions exist, you should have a look at this question: How to remove the space between inline-block elements?

.cell {
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="table" style="width: 100%">
  <div class="row" style="width: 100%">
    <div class="cell" style="width:40%">Last Name</div><!--
    --><div class="cell" style="width:40%">First Name</div><!--
    --><div class="cell" style="width:20%">Age</div>
  </div>
</div></code>```

Body:
I am trying to mimic an HTML table with css classes, but the last "cell" element always gets pushed to the next line.

The way I am currently getting around this is to decrease the width of the last element by a few percent, so that the total width of the elements adds up to ~ 97%. This protects the last element from being pushed to the next line, but it doesn't look as nice because there's unused space at the end.

Is there a way to get the table cells to line up nicely and use 100% of the containing width?

.cell {
  display: inline-block;
}

Last Name

First Name

Age

Body:
This is a well known "problem" with display:inline-block;

One solution is to comment the "space" between your divs.
Other solutions exist, you should have a look at this question: How to remove the space between inline-block elements?

.cell {
  display: inline-block;
}

<div class="table" style="width: 100%">
  <div class="row" style="width: 100%">
    <div class="cell" style="width:40%">Last Name</div><!--
    --><div class="cell" style="width:40%">First Name</div><!--
    --><div class="cell" style="width:20%">Age</div>
  </div>
</div>


问:
Click listener in ViewHolder only sometimes responds
I have the following piece of code. Below you can see my viewholder, adapter and my xml. The problem I'm encountering is that the click is sometimes not executed. Only when I'm also set clicklisteners in my viewholder on the textview and imageview than it works. Presumably the click gets eaten by the textview and imageview. Anybody have any idea why this behaviour occurs.

```<code>class GeneralListItemViewHolder(val view: View) : RecyclerView.ViewHolder(view) {

   var item: GeneralItemViewModel? = null

   init {
       view.setOnClickListener {
            item?.method?.invoke()
       }
   }

   fun bind(item: GeneralItemViewModel) {
      this.item = item
      //Do some nice UI things
   }
}
</code>```

My xml looks like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/ListItem">

<ImageView
    android:id="@+id/general_list_item_icon"
    style="@style/ListItem.Icon"
    android:layout_alignParentStart="true"
    android:layout_centerVertical="true" />

<TextView
    android:id="@+id/general_list_item_title"
    style="@style/ListItem.Labels.Title"
    android:layout_centerVertical="true"
    android:layout_marginStart="@dimen/margin"
    android:layout_toEndOf="@id/general_list_item_icon" />
</code>```

Furthermore my adapter code holds the following:

```<code>class GeneralItemAdapter(val items: List<GeneralItemViewModel>) : RecyclerView.Adapter<GeneralListItemViewHolder>() {

   override fun onBindViewHolder(holder: GeneralListItemViewHolder, position: Int) {
       return holder.bind(getItem(position))
   }

   override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GeneralListItemViewHolder {
       val view = parent.inflate(R.layout.general_list_item, false)
       return GeneralListItemViewHolder(view)
   }

   override fun getItemCount(): Int {
       return items.size
   }

   private fun getItem(position: Int): GeneralItemViewModel {
       return items[position]
   }
}
</code>```

答:
Actually, the issue has to do with the use of synthetic kotlin extension on the view. If you use them on the variable view instead of itemView then the click gets eaten by the textview.</p>

```<code>fun bind(item: AboutGeneralItemViewModel) {
    this.item = item

    itemView.general_list_item_title.text = item.value
    itemView.setOnClickListener {
        item?.method?.invoke()
    }
}
</code>```

Body:
I have the following piece of code. Below you can see my viewholder, adapter and my xml. The problem I'm encountering is that the click is sometimes not executed. Only when I'm also set clicklisteners in my viewholder on the textview and imageview than it works. Presumably the click gets eaten by the textview and imageview. Anybody have any idea why this behaviour occurs.

class GeneralListItemViewHolder(val view: View) : RecyclerView.ViewHolder(view) {

   var item: GeneralItemViewModel? = null

   init {
       view.setOnClickListener {
            item?.method?.invoke()
       }
   }

   fun bind(item: GeneralItemViewModel) {
      this.item = item
      //Do some nice UI things
   }
}

My xml looks like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/ListItem">

<ImageView
    android:id="@+id/general_list_item_icon"
    style="@style/ListItem.Icon"
    android:layout_alignParentStart="true"
    android:layout_centerVertical="true" />

<TextView
    android:id="@+id/general_list_item_title"
    style="@style/ListItem.Labels.Title"
    android:layout_centerVertical="true"
    android:layout_marginStart="@dimen/margin"
    android:layout_toEndOf="@id/general_list_item_icon" />

Furthermore my adapter code holds the following:

class GeneralItemAdapter(val items: List<GeneralItemViewModel>) : RecyclerView.Adapter<GeneralListItemViewHolder>() {

   override fun onBindViewHolder(holder: GeneralListItemViewHolder, position: Int) {
       return holder.bind(getItem(position))
   }

   override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GeneralListItemViewHolder {
       val view = parent.inflate(R.layout.general_list_item, false)
       return GeneralListItemViewHolder(view)
   }

   override fun getItemCount(): Int {
       return items.size
   }

   private fun getItem(position: Int): GeneralItemViewModel {
       return items[position]
   }
}

Body:
Actually, the issue has to do with the use of synthetic kotlin extension on the view. If you use them on the variable view instead of itemView then the click gets eaten by the textview.

fun bind(item: AboutGeneralItemViewModel) {
    this.item = item

    itemView.general_list_item_title.text = item.value
    itemView.setOnClickListener {
        item?.method?.invoke()
    }
}


问:
In akka does a child process run in the same process as its parent actor?
In akka does a child process always run in the same process as its parent actor?

Is there documentation?

答:
By default, all actors are created within the same process (and AppDomain) as their parent. There are few situations where this is not the case:

Remote deployment

Cluster pool routers

In both of those, all parameters send to an actor constructor will be serialized and passed to another machine, which will work as a physical host for an actor instance.


问:
Apply different class to table tr based on image title
```<code><table id='xhtmlgrid'>
<tbody>
<tr class='bgwhite'>
<td>
<table>
<tbody>
<tr>
<td>
<span>
<img src="./secured_off1.png">
</span>
</td>
<td>
<span>
<img src="./secured_off2.png">
</span>
</td>
<td>
<span>
<img src="./secured_off3.png" title="Locked">
</span>
</td>
<td>
<span>
<img src="./secured_off4.png">
</span>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</code>```

i have code like this,based on image title,i have multiple images in that tr, i want to change the tr class from bgwhite to bggreen,how can i do that,any help appreciated.

so far i'm using this code to find the image title

```<code>$("#xhtml_grid table > tbody > tr").each(function () {
        var hdnLock = $(this).find('td:eq(2)').find('img').attr('title');
        if (hdnLock == 'Locked') {
        }

    });
</code>```

for reference i'm adding the image of html

答:
If you only want to change those trs that start out with class="bgwhite", what you need to do is traverse over those explicitly, and then check for each if there's at least one img with title="Locked" inside.

var whiteTrs = document.querySelectorAll('#xhtmlgrid tr.bgwhite');
whiteTrs.forEach(function(tr) {
  if (tr.querySelector('img[title="Locked"]')!=null)
    tr.className = 'bggreen';
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.bgwhite {background:white}
.bggreen {background:green}</code>```

```

Body:
i have code like this,based on image title,i have multiple images in that tr, i want to change the tr class from bgwhite to bggreen,how can i do that,any help appreciated.

so far i'm using this code to find the image title

$("#xhtml_grid table > tbody > tr").each(function () {
        var hdnLock = $(this).find('td:eq(2)').find('img').attr('title');
        if (hdnLock == 'Locked') {
        }

    });

for reference i'm adding the image of html

Body:
If you only want to change those trs that start out with class="bgwhite", what you need to do is traverse over those explicitly, and then check for each if there's at least one img with title="Locked" inside.

var whiteTrs = document.querySelectorAll('#xhtmlgrid tr.bgwhite');
whiteTrs.forEach(function(tr) {
  if (tr.querySelector('img[title="Locked"]')!=null)
    tr.className = 'bggreen';
});

.bgwhite {background:white}
.bggreen {background:green}

<table id='xhtmlgrid'>
<tbody>
<tr class='bgwhite'>
<td>
<table>
<tbody>
<tr>
<td>
<span>
<img src="./secured_off1.png">
</span>
</td>
<td>
<span>
<img src="./secured_off2.png">
</span>
</td>
<td>
<span>
<img src="./secured_off3.png" title="Locked">
</span>
</td>
<td>
<span>
<img src="./secured_off4.png">
</span>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>


问:
Microsoft.CSharp.Core.targets missing
I am building a webservice project on a TFS2017 Update 3 with build tools 2017. I get the following error

C:\Program Files (x86)\Microsoft Visual
  Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.CSharp.CurrentVersion.targets(322,5):
  Error MSB4019: The imported project "C:\Program Files (x86)\Microsoft
  Visual
  Studio\2017\Enterprise\MSBuild\15.0\Bin\Roslyn\Microsoft.CSharp.Core.targets"
  was not found. Confirm that the path in the  declaration is
  correct, and that the file exists on disk.

What steps do I need to take to fix this error?

答:
First suggest you directly use msbuild command on the build agent with TFS build service account. This will narrow down if the issue is related to your agent environment or your TFS build definition.

According to your error info, the path C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Roslyn\Microsoft.CSharp.Core.targets is looking the path of Visual Studio 2017.

However, for Build Tools the path is different should be C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\Roslyn

Seems you haven't installed VS2017 on your build agent. This maybe the root cause of the issue.

The simplest solution is installing VS2017 on your build agent. Note, you need to reconfigure the build agent or restart build agent service to capture those new capabilities. Otherwise you need to change the corresponding import section in your  .csproj project files.

Title: Microsoft.CSharp.Core.targets missing


问:
Xamarin Forms project How to target .NET Framework4.6
I have a Xamarin.Forms project with its pcl targets .netframework4.5

I want to use a nuget package written with .netframework4.6. How can I do it?

I tried to convert my existing pcl project to a .netStandard project, however it didn't work as I multitarget both .netStandart and .netFramework.

Then I tried to convert the .netStandart classLibrary Project to a project that targets only .netFramework4.6 and reference it from my pcl project. I couldn't reference it neither from my pcl nor from my .droid project as .netFramework4.6 is not supported.

I am developing an Android app, therefore it is enough for me to find a solution that works only for Android.

Thanks in advance!!

答: Unfortinalty, you can't change it to 4.6. The thing is that Xamarin uses a special profile to work with .NET Frameworks 4.5. It's custom configured to work with mobile devices. So untill Xamarin (now Microsoft) came out with a new profile for Xamarin that tartget .NET Framework 4.6, you can't change the version of it. </p>


问:
WireFrame of Json formated geometry in Three.js
I would like to display the wireframe of a parallelepiped defined by vertexes in a Json  format using the following Three.js code

```<code>var testCube ={
                "metadata":{
                "version":json['version'],
                "type":json['type'],
                "uvs":json['n_uvs'],
                "normals":json['n_normals'],
                "faces":json['n_faces'],
                "generator":"io_three",
                "vertices":json['n_vertices'],
                                            },
                "faces":json['faces'],
                "vertices":json['vertices'],
                "normals":json['normals'],
                "uvs":[],
                "name":json['name']}

var loader = new THREE.JSONLoader();

var model = loader.parse( testCube );

meshBox = new THREE.Mesh( model.geometry, model.materials[ 0 ] );

var geo = new THREE.EdgesGeometry( meshBox.geometry );

var mat = new THREE.LineBasicMaterial( { color: 0xffffff, linewidth: 2 });

var wireframe = new THREE.LineSegments( geo, mat );

scene.add( wireframe );
</code>```

however, the above code produce this kind of visualization:

while I would like to produce a visualization where also the internal wireframe is visible as the following:

Question: do you know how I can modify the above Three.js code to produce a full wireframe as displayed in the second picture?

Upadate: using the function WireframeGeometry you have the following plot:

Diagonals appear on each face of the mesh. Do yo know a function that does not produce diagonals?

Thank you very much for your help!

答:
The solution is rough and imperfect, and it's a huge field for improvement and optimization.

You create one geometry and share it between two instances of THREE.LineSegments() for opposing sides of a box.

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(-15, 10, 10);
var renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

scene.add(new THREE.AmbientLight(0xffffff, .5));
var light = new THREE.DirectionalLight(0xffffff, .5);
light.position.setScalar(10);
scene.add(light);

var box = new THREE.Mesh(new THREE.BoxGeometry(10, 5, 5, 5, 5, 5), new THREE.MeshLambertMaterial({color:"gray"}));
scene.add(box);

var material = new THREE.LineBasicMaterial({
  vertexColors: THREE.VertexColors
});
var params = box.geometry.parameters;
var geometryGridXY = Grid(params.width, params.height, params.widthSegments, params.heightSegments, "yellow");
var gridXYFront = new THREE.LineSegments(geometryGridXY, material);
gridXYFront.position.z = params.depth / 2 + 0.001;
box.add(gridXYFront);
var gridXYBack = new THREE.LineSegments(geometryGridXY, material);
gridXYBack.position.z = -params.depth / 2 - 0.001;
box.add(gridXYBack);

var geometryGridYZ = Grid(params.height, params.depth, params.heightSegments, params.depthSegments, "aqua");
var gridYZLeft = new THREE.LineSegments(geometryGridYZ, material);
gridYZLeft.position.x = -params.width / 2 - 0.001;
gridYZLeft.rotation.y = -Math.PI * .5;
box.add(gridYZLeft);

render();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  overflow: hidden;
  margin: 0;
}</code>```

```

Body:
I would like to display the wireframe of a parallelepiped defined by vertexes in a Json  format using the following Three.js code

var testCube ={
                "metadata":{
                "version":json['version'],
                "type":json['type'],
                "uvs":json['n_uvs'],
                "normals":json['n_normals'],
                "faces":json['n_faces'],
                "generator":"io_three",
                "vertices":json['n_vertices'],
                                            },
                "faces":json['faces'],
                "vertices":json['vertices'],
                "normals":json['normals'],
                "uvs":[],
                "name":json['name']}

var loader = new THREE.JSONLoader();

var model = loader.parse( testCube );

meshBox = new THREE.Mesh( model.geometry, model.materials[ 0 ] );

var geo = new THREE.EdgesGeometry( meshBox.geometry );

var mat = new THREE.LineBasicMaterial( { color: 0xffffff, linewidth: 2 });

var wireframe = new THREE.LineSegments( geo, mat );

scene.add( wireframe );

however, the above code produce this kind of visualization:

while I would like to produce a visualization where also the internal wireframe is visible as the following:

Question: do you know how I can modify the above Three.js code to produce a full wireframe as displayed in the second picture?

Upadate: using the function WireframeGeometry you have the following plot:

Diagonals appear on each face of the mesh. Do yo know a function that does not produce diagonals?

Thank you very much for your help!

Body:
The solution is rough and imperfect, and it's a huge field for improvement and optimization.

You create one geometry and share it between two instances of THREE.LineSegments() for opposing sides of a box.

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(-15, 10, 10);
var renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

scene.add(new THREE.AmbientLight(0xffffff, .5));
var light = new THREE.DirectionalLight(0xffffff, .5);
light.position.setScalar(10);
scene.add(light);

var box = new THREE.Mesh(new THREE.BoxGeometry(10, 5, 5, 5, 5, 5), new THREE.MeshLambertMaterial({color:"gray"}));
scene.add(box);

var material = new THREE.LineBasicMaterial({
  vertexColors: THREE.VertexColors
});
var params = box.geometry.parameters;
var geometryGridXY = Grid(params.width, params.height, params.widthSegments, params.heightSegments, "yellow");
var gridXYFront = new THREE.LineSegments(geometryGridXY, material);
gridXYFront.position.z = params.depth / 2 + 0.001;
box.add(gridXYFront);
var gridXYBack = new THREE.LineSegments(geometryGridXY, material);
gridXYBack.position.z = -params.depth / 2 - 0.001;
box.add(gridXYBack);

var geometryGridYZ = Grid(params.height, params.depth, params.heightSegments, params.depthSegments, "aqua");
var gridYZLeft = new THREE.LineSegments(geometryGridYZ, material);
gridYZLeft.position.x = -params.width / 2 - 0.001;
gridYZLeft.rotation.y = -Math.PI * .5;
box.add(gridYZLeft);

render();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);

}

body {
  overflow: hidden;
  margin: 0;
}

<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<script>

  function Grid(width, height, widthSegments, heightSegments, color) {

    width = width || 1;
    height = height || 1;
    widthSegments = widthSegments || 1;
    heightSegments = heightSegments || 1;
    color = new THREE.Color(color !== undefined ? color : 0x444444);

    var stepWidth = width / widthSegments;
    var stepHeight = height / heightSegments;
    var halfWidth = width / 2;
    var halfHeight = height / 2;

    var vertices = [],
      colors = [], j = 0;

    for (let i = 0, k = -halfHeight; i <= heightSegments; i++, k += stepHeight) {

      vertices.push(-halfWidth, k, 0, halfWidth, k, 0);

      color.toArray(colors, j); j += 3;
      color.toArray(colors, j); j += 3;
    }

    for (let i = 0, k = -halfWidth; i <= widthSegments; i++, k += stepWidth) {

      vertices.push(k, halfHeight, 0, k, -halfHeight, 0);

      color.toArray(colors, j); j += 3;
      color.toArray(colors, j); j += 3;
    }

    var geometry = new THREE.BufferGeometry();
    geometry.addAttribute('position', new THREE.BufferAttribute(new Float32Array(vertices), 3));
    geometry.addAttribute('color', new THREE.BufferAttribute(new Float32Array(colors), 3));

    return geometry;

  }

</script>


问:
Is the my cassandra config implement true
I have a cassandra cluster with three nodes under normal circumstances. When I send write request cluster from node.js, I want all nodes to write back to me after writing, while reading, i want to be able to read which node I am connected to. I want this setup to continue when one of the three nodes has died. I chose replication factor= 3 consistency=2
How should I implement a configuration. Is the config implement true ?
With my respects...</p>

答:
So I unfortunately have no real clue about the provided numbers from the node JS driver, but I know something about the consistency levels, which I suspect you are using in the background, assuming that you are using this driver: http://datastax.github.io/nodejs-driver/.

Just a basic thing: The nodes don't write back to you directly, but your query is sent to one node, the coordinator of that query, which then distributes the query in your cluster according to your consistency level specifications (at least if it's a simple query, more complex destribution logic applies in case of batch queries). The coordinator then reports back to you when the query is executed.

Whether your requirements can be fulfilled at all depends on the replication factor you chose. The problem here is that cassandra only knows so many of them. The options for writing are: all (which at first looks what you want), quorum (which is also an option), one and any. So let's assume you choose all, because you want to write to all replicas. That's totally fine, but if one of the nodes goes down, there will be failing writes, because one of the replicas could not be updated. In case you are actually using replication factor 3, you can fallback to write with quorum, which is 2 nodes in this case. What should happen if another node fails? I know, very unlikely, but I've seen it in production, so it happens from time to time. Should the single last node be updated in this case? Then you need to fallback to consistency level 1. Everything fine.

But what if you choose the replication factor to be 5? Well, there is no way of saying: I want 4 nodes. You can only have a quorum in case of a failure of one node, and that would be 3, not 4. And the next fallback would be 1 and not 2.

The final question is: if you lose one node and you do a fallbak in the writing part, what happens when your node comes back (assuming that there are lost updates because some of the hinted handoffs are already discarded)? The reading part of your application can always read stale data because you always only read from a single node. It seems to me like you are trying to compensate for that in the write part. My personal idea would be using quorum when reading and writing, this way it's guaranteed that you read current data and a single node can go down (with replication factor 5 it's even 2 nodes). Also keep in mind that when you write to a node, cassandra will always attempt to write to the replicas in the background, so it tries to keep your data up to date. The risk of reading stale data even with a consistency level pair of one-one can be acceptable if you really need the speed.


问:
Need Help to Visualize Atom contact in Delaunay Triangulation
I am new to CGAL . I am working on a school project to compute the Delaunay Triangulation of Protein structure . How can I visualize the DT structure in Mesh lab . I tried using Poison surface reconstruction, but PSR is using constrained DT and adding new edges which is not I want.

I want to visualize the edge contacts between 3d atom points in Delaunay
Triangulation. Could anyone help me.

答:
Poisson surface reconstruction is not using constrained Delaunay Triangulation, it is defining a function which 0-level is meshed using the CGAL surface mesher.
If you want to compute the Delaunay triangulation of a point set, simply use the class Delaunay_triangulation_3. The best way to visualize the triangulation is to display its edges. I don't think meshlab is able to display polylines but I think it is pretty straight forward to modify one of the example provided by CGAL, extract the edges of the triangulation and generate for example a CGO that you can open in PyMol in addition to your protein structure.


问:
Finding combinations of a list of numbers – not that "normal" way
I've searched now for more than two days around the web for any working solution. But maybe I just need the right "word" to google for. Let me explain, what I want. Just found lot of articles of combinations and permutations, but they're not covering my requirements (or I don't understand how to do this).

Let's assume, that I'll have a list of numbers: [1, 2, 3]

Now, I want all possible combinations of them.
I need that kind of result (for the given example):

```<code>1 2 3
1 2+3
1+2+3
2 1+3
3 1+2
</code>```

Those are all available combinations (hope so). I don't need repetition, so 1 2+3 is the same as 1 3+2.

Is there any Math genius who may help me with it? Is there any formula I can calculate the result count?

Trying to solve it in PHP but it oftens end in endless recursive executions and a memory limit exception.

答:
As already mentioned in the comment above, I found a solution for this problem.

A helpful (Python) script is posted in here:
Set partitions in Python

For those, who need it in PHP, in here my conversion:

```<code>// recursive function
function partition($collection) {
    if (count($collection) == 1) {
        yield array($collection);
        return;
    }

    $first = $collection[0];

    foreach (partition(array_slice($collection, 1)) as $smaller) {
      foreach ($smaller as $n => $subset) {
        yield array_merge(
            array_slice($smaller, 0, $n),
            array(array_merge(array($first), $subset)),
            array_slice($smaller, $n + 1)
        );
      }

      yield array_merge(array(array($first)), $smaller);
    }
}

// set up an array
$something = array(1, 2, 3, 4);

// loop all the variants
foreach (partition($something) as $n => $p) {
    var_dump($p);
}
</code>```

Body:
I've searched now for more than two days around the web for any working solution. But maybe I just need the right "word" to google for. Let me explain, what I want. Just found lot of articles of combinations and permutations, but they're not covering my requirements (or I don't understand how to do this).

Let's assume, that I'll have a list of numbers: [1, 2, 3]

Now, I want all possible combinations of them.
I need that kind of result (for the given example):

1 2 3
1 2+3
1+2+3
2 1+3
3 1+2

Those are all available combinations (hope so). I don't need repetition, so 1 2+3 is the same as 1 3+2.

Is there any Math genius who may help me with it? Is there any formula I can calculate the result count?

Trying to solve it in PHP but it oftens end in endless recursive executions and a memory limit exception.

Body:
As already mentioned in the comment above, I found a solution for this problem.

A helpful (Python) script is posted in here:
Set partitions in Python

For those, who need it in PHP, in here my conversion:

// recursive function
function partition($collection) {
    if (count($collection) == 1) {
        yield array($collection);
        return;
    }

    $first = $collection[0];

    foreach (partition(array_slice($collection, 1)) as $smaller) {
      foreach ($smaller as $n => $subset) {
        yield array_merge(
            array_slice($smaller, 0, $n),
            array(array_merge(array($first), $subset)),
            array_slice($smaller, $n + 1)
        );
      }

      yield array_merge(array(array($first)), $smaller);
    }
}

// set up an array
$something = array(1, 2, 3, 4);

// loop all the variants
foreach (partition($something) as $n => $p) {
    var_dump($p);
}


问:
Why is "git pull origin feature-12345 master" the only way to update my pull request branch?
I'm working with a pull request on BitBucket, which has been open for a fairly long time (several weeks, while master continues to progress rapidly), and where I'm not the only person making commits to the PR. I also need to keep the PR in sync with master. Because there are multiple people working on the branch (and because it feels dirty), doing a rebase and then git push --force is not a great option.

The only thing that I've found actually works, in this case, is the following:

```<code>git checkout master
git pull origin master
git checkout -b feature-12345 origin/feature-12345
git pull origin feature-12345 master
git push origin feature-12345
</code>```

The key line above is git pull origin feature-12345 master, which results in a commit with the message:

```<code>Merge branches 'feature-12345' and 'master' of ssh://mybitbucketserver/ABC/xyz into feature-12345
</code>```

After doing this, BitBucket shows a nice "merge" commit in the "commits" list for the PR, instead of flooding the commit history with recent commits from master.

I'm happy that I've worked out how to do this, but my question is: why do I need to use that specific command, to make it merge in this way? If I try (while on the feature-12345 branch):

```<code>git pull origin master
</code>```

And then push, it floods my commit history.

Same if I do this (which I would have thought would be 100% equivalent to the merge part of git pull origin feature-12345 master, but it seems not):

```<code>git merge feature-12345 master
</code>```

What's so special about git pull origin feature-12345 master?

答:
git pull is nothing more than a fetch followed by a merge.

git pull feature-12345 master updates your remote branches origin/feature-12345 and origin/master, then it merges both of these into your current HEAD.

I'm not sure why git pull origin master makes bitbucket show the whole history of master, my guess is that it gets confused by the merge branch being a remote branch (origin/master, compared to just master), or possibly because you merge two branches (origin/master and origin/feature-12345) into a third one (feature-12345)

Let me suggest to first get your master up-to-date, merge locally to you branch, then push the resulting branch:

```<code>git checkout master
git pull origin master # keep your master branch up to date
git checkout feature-12345
git merge master # to get new features from master, resolve conflicts...
git push origin feature-12345 # push the merge commit to bitbucket
</code>```

Body:
I'm working with a pull request on BitBucket, which has been open for a fairly long time (several weeks, while master continues to progress rapidly), and where I'm not the only person making commits to the PR. I also need to keep the PR in sync with master. Because there are multiple people working on the branch (and because it feels dirty), doing a rebase and then git push --force is not a great option.

The only thing that I've found actually works, in this case, is the following:

git checkout master
git pull origin master
git checkout -b feature-12345 origin/feature-12345
git pull origin feature-12345 master
git push origin feature-12345

The key line above is git pull origin feature-12345 master, which results in a commit with the message:

Merge branches 'feature-12345' and 'master' of ssh://mybitbucketserver/ABC/xyz into feature-12345

After doing this, BitBucket shows a nice "merge" commit in the "commits" list for the PR, instead of flooding the commit history with recent commits from master.

I'm happy that I've worked out how to do this, but my question is: why do I need to use that specific command, to make it merge in this way? If I try (while on the feature-12345 branch):

git pull origin master

And then push, it floods my commit history.

Same if I do this (which I would have thought would be 100% equivalent to the merge part of git pull origin feature-12345 master, but it seems not):

git merge feature-12345 master

What's so special about git pull origin feature-12345 master?

Body:
git pull is nothing more than a fetch followed by a merge.

git pull feature-12345 master updates your remote branches origin/feature-12345 and origin/master, then it merges both of these into your current HEAD.

I'm not sure why git pull origin master makes bitbucket show the whole history of master, my guess is that it gets confused by the merge branch being a remote branch (origin/master, compared to just master), or possibly because you merge two branches (origin/master and origin/feature-12345) into a third one (feature-12345)

Let me suggest to first get your master up-to-date, merge locally to you branch, then push the resulting branch:

git checkout master
git pull origin master # keep your master branch up to date
git checkout feature-12345
git merge master # to get new features from master, resolve conflicts...
git push origin feature-12345 # push the merge commit to bitbucket


问:
Best continuous integration setup for multi-platform development
What is the best continuous integration setup for a Devleopment department that codes in multiple environments?

At my company we write some code in C# and some in Java, I've previously used CC.Net but I've never done CInt with Java.

I'm aware of Continuum and was recently told about Hudson, but I've never used either.

Would it be better to use two CInt services one for each platform or to use a single one for both?

答:
As you already know how to use CC.Net and CC.NET can run any build task that outputs XML.  Why not just use CC.NET with ant for your java code as well as your C# code.

Or do you need to build on none Windows machine?  CC.NET may work with mono, I have not checked.

Remember that any continuous integration setup that compiles all your code and run your unit tests give you great benefits.  On most projects having the perfect setup only give a smaller improvement over having a continuous integration setup that works.  So I would just pick something you are happy with and start using it now.

OwnerDisplayName: Omar Kooheji

OwnerDisplayName: Ian Ringrose


问:
If I wanted to change $_GET to $_POST in this code What would I do?
I can't seem to figure out how to post this instead of using get, I've found that you have to use a form but that's about it.
If anyone is willing to provide an answer that'd be awesome!
Thank you!!!!
.............................................................................................................................................................</p>

```<code><!DOCTYPE html>
<html>
<head>
 <meta charset="UTF-8">
<title>Portfolio Max</title>

<link rel="stylesheet" type="text/css" href="./style.css">
</head>
<body>

  <div class= "header">
    <h1 id= "textinheader">Portfolio</h1></div>
    <div class= "portfolio text"> </div>

    <div class="menu">
        <a href="?page=1">pagina 1</a>
        <a href="?page=2">pagina2</a>
        <div class="dropdown">
          <button class="dropbutton">Meer
            <i class="down"></i>
          </button>
          <div class="dropdown-content">
            <a href="?page=3">pagina 3</a>
            <a href="?page=4">pagina 4</a>
            <a href="?page=5">pagina 5</a>
          </div>
        </div>
      </div>

    <?php  echo date("Y/M/D h:i:sa");?>

    </div>

   <?php

   /*
   if( $_GET ['page'] == '1')
   include 'page1.php';
   else
   include 'page2.php';
   */
  if (! isset($_GET ['page']))
  $_GET = array_merge( $_GET, array('page'=>1));

  include 'page'.$_GET ['page'].'.php';

   ?>

    </div>

 </body>
</html>c
</code>```

答: you can't in php, if you are sending data via url parameters, the only way to retrieve this data from the url is via GET. you can read more on GET here. you will have to use GET to retrieve the page number from the page parameter. you can try javascript, get the values of the url and use POST to send the value to another .php file. From your code I assume this is for pagination, why do you need to $_POST rather than $_GET

Body:
I can't seem to figure out how to post this instead of using get, I've found that you have to use a form but that's about it.
If anyone is willing to provide an answer that'd be awesome!
Thank you!!!!
.............................................................................................................................................................

<!DOCTYPE html>

 <meta charset="UTF-8">
<title>Portfolio Max</title>

<link rel="stylesheet" type="text/css" href="./style.css">

Portfolio

        pagina 1
        pagina2

          <button class="dropbutton">Meer

          </button>

            pagina 3
            pagina 4
            pagina 5

    <?php  echo date("Y/M/D h:i:sa");?>

   <?php

   /*
   if( $_GET ['page'] == '1')
   include 'page1.php';
   else
   include 'page2.php';
   */
  if (! isset($_GET ['page']))
  $_GET = array_merge( $_GET, array('page'=>1));

  include 'page'.$_GET ['page'].'.php';

   ?>

c


问:
jquery css, css gradients
I'm trying to apply css gradients to a specific div using the jquery css feature and can't quite seem to get it working.  I don't have access to the style sheet and am having trouble because I"m trying to apply it several times to appease cross browser issues.  I'm just not quite sure why this isn't working, any thoughts?  Thanks in advance</p>

```<code>$(document).ready(function() {
//Build your CSS.
var gradient1 = {
    "background":     "-moz-linear-gradient(top,  #fbfbfb 0%, #f4f4f5 100%)"
};
var gradient2 = {
    "background":     "-webkit-linear-gradient(top,  #fbfbfb 0%,#f4f4f5 100%)"
};
var gradient3 = {
    "background":     "-o-linear-gradient(top,  #fbfbfb 0%,#f4f4f5 100%)"
};
var gradient4 = {
    "background":      "-ms-linear-gradient(top,  #fbfbfb 0%,#f4f4f5 100%); /* IE10+ */ background: linear-
gradient(to bottom,  #fbfbfb 0%,#f4f4f5 100%)"
};
var gradient5 = {
    "filter":     " progid:DXImageTransform.Microsoft.gradient(startColorstr=#fbfbfb, endColorstr=# f4f4f5)"
};

//Apply your CSS to the body tag.  You can enter any tag here, as
//well as ID's and Classes.
$("#service_DESCRIPTION").css(gradient1);
$("#service_FAQ").css(gradient1);

$("#service_DESCRIPTION").css(gradient2);
$("#service_FAQ").css(gradient2);

$("#service_DESCRIPTION").css(gradient3);
$("#service_FAQ").css(gradient3);

$("#service_DESCRIPTION").css(gradient4);
$("#service_FAQ").css(gradient4);

$("#service_DESCRIPTION").css(gradient5);
$("#service_FAQ").css(gradient5);

});
</code>```

答:
Remove this:</p>

```<code>; /* IE10+ */ background: linear-gradient(to bottom,  #fbfbfb 0%,#f4f4f5 100%)
</code>```

Title: jquery css, css gradients

Body:
I'm trying to apply css gradients to a specific div using the jquery css feature and can't quite seem to get it working.  I don't have access to the style sheet and am having trouble because I"m trying to apply it several times to appease cross browser issues.  I'm just not quite sure why this isn't working, any thoughts?  Thanks in advance

$(document).ready(function() {
//Build your CSS.
var gradient1 = {
    "background":     "-moz-linear-gradient(top,  #fbfbfb 0%, #f4f4f5 100%)"
};
var gradient2 = {
    "background":     "-webkit-linear-gradient(top,  #fbfbfb 0%,#f4f4f5 100%)"
};
var gradient3 = {
    "background":     "-o-linear-gradient(top,  #fbfbfb 0%,#f4f4f5 100%)"
};
var gradient4 = {
    "background":      "-ms-linear-gradient(top,  #fbfbfb 0%,#f4f4f5 100%); /* IE10+ */ background: linear-
gradient(to bottom,  #fbfbfb 0%,#f4f4f5 100%)"
};
var gradient5 = {
    "filter":     " progid:DXImageTransform.Microsoft.gradient(startColorstr=#fbfbfb, endColorstr=# f4f4f5)"
};

//Apply your CSS to the body tag.  You can enter any tag here, as
//well as ID's and Classes.
$("#service_DESCRIPTION").css(gradient1);
$("#service_FAQ").css(gradient1);

$("#service_DESCRIPTION").css(gradient2);
$("#service_FAQ").css(gradient2);

$("#service_DESCRIPTION").css(gradient3);
$("#service_FAQ").css(gradient3);

$("#service_DESCRIPTION").css(gradient4);
$("#service_FAQ").css(gradient4);

$("#service_DESCRIPTION").css(gradient5);
$("#service_FAQ").css(gradient5);

});

Body:
Remove this:

; /* IE10+ */ background: linear-gradient(to bottom,  #fbfbfb 0%,#f4f4f5 100%)


问:
comparing three variables
I have three integer variables: firstCount, secondCount, thirdCount. I need to compare it and to output the result. I'm bad at SQL, but C# code is something like this:

```<code>if(firstCount == secondCount == thirdCount)
  return true;
else
  return false;
</code>```

答:
Try the code ,</p>

```<code>if ( (firstCount = secondCount) and (secondCount = thirdCount) and (firstCount = ThirdCount) )
  return true;
else
  return false;
</code>```

Title: comparing three variables

Body:
I have three integer variables: firstCount, secondCount, thirdCount. I need to compare it and to output the result. I'm bad at SQL, but C# code is something like this:

if(firstCount == secondCount == thirdCount)
  return true;
else
  return false;

Body:
Try the code ,

if ( (firstCount = secondCount) and (secondCount = thirdCount) and (firstCount = ThirdCount) )
  return true;
else
  return false;


问:
how to change icon colors dynamically in react js
how to change icons colors dynamically below here:

```<code>var byillingvalues=[];
for(var i in this.state.Alldata){
  byillingvalues.push({bycdata:this.state.Alldata[i].label})
}

var values=byillingvalues.map(function(d,idx){
        let colors=["#F0F8FF","#FFE4C4","#8A2BE2"];
        for(var i=0;i<=colors.length;i++){
              if(i==idx){
               return (<span key={idx}>{<i className="fa fa-square" aria-
                hidden="true" color:colors[i]></i>} {d.bycdata}   </span>);
             }

        }

});
</code>```

How to change icon colors dynamically in react?

答:
You can pass properties to objects in react using the following </p>

```<code>class IconList extends Component {
  render() {
    let colors=["#F0F8FF","#FFE4C4","#8A2BE2"];
    return (
      {
        for(var i=0;i<=colors.length;i++) {
          <i
            className="fa fa-square"
            aria-hidden="true"
            style={{color: colors[i]}}
          />
        }
      }
    )
  }
</code>```

Body:
how to change icons colors dynamically below here:

var byillingvalues=[];
for(var i in this.state.Alldata){
  byillingvalues.push({bycdata:this.state.Alldata[i].label})
}

var values=byillingvalues.map(function(d,idx){
        let colors=["#F0F8FF","#FFE4C4","#8A2BE2"];
        for(var i=0;i<=colors.length;i++){
              if(i==idx){
               return ({} {d.bycdata}   );
             }

        }

});

How to change icon colors dynamically in react?

Body:
You can pass properties to objects in react using the following

class IconList extends Component {
  render() {
    let colors=["#F0F8FF","#FFE4C4","#8A2BE2"];
    return (
      {
        for(var i=0;i<=colors.length;i++) {
          <i
            className="fa fa-square"
            aria-hidden="true"
            style={{color: colors[i]}}
          />
        }
      }
    )
  }


问:
MongoDB shell syntax error issue
Given this document:

```<code>{
  "_id": 0,
  "name": "Usman Shehu",
  "dp": "ol.jpg",
  "contacts": [
    {
      "id": 0,
      "name": "Ahmad Sani",
      "dp": "ol.jpg",
      "m": "Messages:12",
      "time": "01:27am",
      "chats": [
        {
          "msg": "hello there",
          "t": "12:45am",
          "des": "from"
        },
        {
          "msg": "how far...",
          "t": "12:47am",
          "des": "to"
        },
        {
          "msg": "so far so good",
          "t": "01:05pm",
          "des": "from"
        }
      ]
    }
  ]
}
</code>```

If i try to run this query ...

```<code>db.gist.update({"contacts.id":0},{$push:{chats:{"msg":"Test4","des":"from","t":"06:38pm"}}})
</code>```

... it is not updating the "chats" array but adding it as new field in the within the document.

Please any help?

答:
This will work:

```<code>db.gist.update({"contacts.id":0},{$push:{"contacts.$.chats":{"msg":"Test4","des":"from","t":"06:38pm"}}})
</code>```

You have to specify contacts.$.chat for the $push command, because contacts.chat is a nested array you have to use the positional operator.

Running the above command against the document supplied in your question produces the following, updated, document:

```<code>{
    "_id" : 0,
    "name" : "Usman Shehu",
    "dp" : "ol.jpg",
    "contacts" : [
        {
            "id" : 0,
            "name" : "Ahmad Sani",
            "dp" : "ol.jpg",
            "m" : "Messages:12",
            "time" : "01:27am",
            "chats" : [
                {
                    "msg" : "hello there",
                    "t" : "12:45am",
                    "des" : "from"
                },
                {
                    "msg" : "how far...",
                    "t" : "12:47am",
                    "des" : "to"
                },
                {
                    "msg" : "so far so good",
                    "t" : "01:05pm",
                    "des" : "from"
                },
                {
                    "msg" : "Test4",
                    "des" : "from",
                    "t" : "06:38pm"
                }
            ]
        }
    ]
}
</code>```

Note: the docs state that:

the positional $ operator acts as a placeholder for the first match of the update query document.

Your update query document ({"contacts.id":0}) uses an id which suggests that there is only one expected match so using the positional operator should be ok for your use case. However, it's worth noting that if the update query document matches multiple contacts then only the first matched contact will be updated.

Title: MongoDB shell syntax error issue

Body:
Given this document:

{
  "_id": 0,
  "name": "Usman Shehu",
  "dp": "ol.jpg",
  "contacts": [
    {
      "id": 0,
      "name": "Ahmad Sani",
      "dp": "ol.jpg",
      "m": "Messages:12",
      "time": "01:27am",
      "chats": [
        {
          "msg": "hello there",
          "t": "12:45am",
          "des": "from"
        },
        {
          "msg": "how far...",
          "t": "12:47am",
          "des": "to"
        },
        {
          "msg": "so far so good",
          "t": "01:05pm",
          "des": "from"
        }
      ]
    }
  ]
}

If i try to run this query ...

db.gist.update({"contacts.id":0},{$push:{chats:{"msg":"Test4","des":"from","t":"06:38pm"}}})

... it is not updating the "chats" array but adding it as new field in the within the document.

Please any help?

Body:
This will work:

db.gist.update({"contacts.id":0},{$push:{"contacts.$.chats":{"msg":"Test4","des":"from","t":"06:38pm"}}})

You have to specify contacts.$.chat for the $push command, because contacts.chat is a nested array you have to use the positional operator.

Running the above command against the document supplied in your question produces the following, updated, document:

{
    "_id" : 0,
    "name" : "Usman Shehu",
    "dp" : "ol.jpg",
    "contacts" : [
        {
            "id" : 0,
            "name" : "Ahmad Sani",
            "dp" : "ol.jpg",
            "m" : "Messages:12",
            "time" : "01:27am",
            "chats" : [
                {
                    "msg" : "hello there",
                    "t" : "12:45am",
                    "des" : "from"
                },
                {
                    "msg" : "how far...",
                    "t" : "12:47am",
                    "des" : "to"
                },
                {
                    "msg" : "so far so good",
                    "t" : "01:05pm",
                    "des" : "from"
                },
                {
                    "msg" : "Test4",
                    "des" : "from",
                    "t" : "06:38pm"
                }
            ]
        }
    ]
}

Note: the docs state that:

the positional $ operator acts as a placeholder for the first match of the update query document.

Your update query document ({"contacts.id":0}) uses an id which suggests that there is only one expected match so using the positional operator should be ok for your use case. However, it's worth noting that if the update query document matches multiple contacts then only the first matched contact will be updated.


问:
Only the last element is shown in Firebase database
I have a sample database in Firebase that is meant to display some facts. Currently, I want the textview to display all the five sample facts 1,2,3,4,5..but it shows only the last one. Where should I modify on my code?

Java sample:

```<code>fact = database.getInstance().getReference().child("Facts");

        fact.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){

                    Fact factdata = postSnapshot.getValue(Fact.class);

                    factViewBox.setText(factdata.getFactDetail());

                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
</code>```

And the json:

```<code>"Facts":{
    "01":{
   "factDetail":"1"
   }
,

"02":{
   "factDetail":"2"
}
,
"03":{
   "factDetail":"3"
}
,
"04":{
   "factDetail":"4"
}
,
"05":{
   "factDetail":"5"
}

}
</code>```

答:
```<code> for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
    Fact factdata = postSnapshot.getValue(Fact.class);
    if(factViewBox.getText().length() > 0 ){
         factViewBox.setText(factViewBox.getText() + "\n" + factdata.getFactDetail());
    }else{
         factViewBox.setText(factdata.getFactDetail());
    }
 }
</code>```

you need to change in the for loop

Body:
I have a sample database in Firebase that is meant to display some facts. Currently, I want the textview to display all the five sample facts 1,2,3,4,5..but it shows only the last one. Where should I modify on my code?

Java sample:

fact = database.getInstance().getReference().child("Facts");

        fact.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){

                    Fact factdata = postSnapshot.getValue(Fact.class);

                    factViewBox.setText(factdata.getFactDetail());

                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

And the json:

"Facts":{
    "01":{
   "factDetail":"1"
   }
,

"02":{
   "factDetail":"2"
}
,
"03":{
   "factDetail":"3"
}
,
"04":{
   "factDetail":"4"
}
,
"05":{
   "factDetail":"5"
}

}

Body:
 for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
    Fact factdata = postSnapshot.getValue(Fact.class);
    if(factViewBox.getText().length() > 0 ){
         factViewBox.setText(factViewBox.getText() + "\n" + factdata.getFactDetail());
    }else{
         factViewBox.setText(factdata.getFactDetail());
    }
 }

you need to change in the for loop


问:
Non-resolvable import POM Failure to find
I experimented with spring boot like module in parent pom and now I get error

```<code>[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[ERROR] Non-resolvable import POM: Failure to find org.springframework.boot:spring-boot-dependencies:pom:2.0.0.M6 in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced @ line 30, column 19
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project mydomain.project:main-project:1.0-SNAPSHOT (D:\gitProjects\main-server\sources\pom.xml) has 1 error
[ERROR]     Non-resolvable import POM: Failure to find org.springframework.boot:spring-boot-dependencies:pom:2.0.0.M6 in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced @ line 30, column 19 -> [Help 2]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException
</code>```

I tried delete myproject in .m2 local repo

I have maven project with 2 modules(simple java and spring boot). I extract parent from spring boot to main pom like dependensyManagment and set paren to spring boot - main project. After that I get this error

I revert changes and all works fine. The step by step I faunt point when all crush

I add this to main pom

```<code><dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>2.0.0.M6</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>   </dependencyManagement>
</code>```

in spring boot I change this

```<code><parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.0.0.M6</version>
      <relativePath/> <!-- lookup parent from repository -->
  </parent>
</code>```

to this:

```<code><parent>
        <artifactId>main-project</artifactId>
        <groupId>main.project</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
</code>```

答:
The version 2.0.0.M6 isn't located in the repo http://repo.maven.apache.org/maven2. If you wan't to use this version you have to use the maven repo http://repo.spring.io/milestone. So add it to your POM file:

<repositories>
    <repository>
        <id>spring-milestone-repo</id>
        <url>http://repo.spring.io/milestone/</url>
    </repository>
</repositories>
```

<p>I would recommend you to use the latest release version of spring-boot (1.5.8.RELEASE), not a milestone version. I don't know how your POM looks like, but you can define spring boot in your POM in different ways:</p>

<h1>1. Using the Spring Boot parent POM</h1>

```<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
</parent>
```

<p>Then you can add the dependencies you wish to use e.g.:</p>

```<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>
```

<p>See: https://spring.io/guides/gs/spring-boot/</p>

<h1>2. Declare Spring-Boot in Dependency-Management</h1>

<p>If you already using an own parent POM, you could also import the spring boot dependency management in your POM:</p>

```<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>1.5.8.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
```

Same as in variant #1 you can declare afterwards the dependencies of spring boot you wish to use.

Body:
I experimented with spring boot like module in parent pom and now I get error

[ERROR] [ERROR] Some problems were encountered while processing the POMs:
[ERROR] Non-resolvable import POM: Failure to find org.springframework.boot:spring-boot-dependencies:pom:2.0.0.M6 in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced @ line 30, column 19
 @
[ERROR] The build could not read 1 project -> [Help 1]
[ERROR]
[ERROR]   The project mydomain.project:main-project:1.0-SNAPSHOT (D:\gitProjects\main-server\sources\pom.xml) has 1 error
[ERROR]     Non-resolvable import POM: Failure to find org.springframework.boot:spring-boot-dependencies:pom:2.0.0.M6 in https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced @ line 30, column 19 -> [Help 2]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/ProjectBuildingException
[ERROR] [Help 2] http://cwiki.apache.org/confluence/display/MAVEN/UnresolvableModelException

I tried delete myproject in .m2 local repo

I have maven project with 2 modules(simple java and spring boot). I extract parent from spring boot to main pom like dependensyManagment and set paren to spring boot - main project. After that I get this error

I revert changes and all works fine. The step by step I faunt point when all crush

I add this to main pom

<dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>2.0.0.M6</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>   </dependencyManagement>

in spring boot I change this

<parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.0.0.M6</version>
      <relativePath/>
  </parent>

to this:

<parent>
        <artifactId>main-project</artifactId>
        <groupId>main.project</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>

Body:
The version 2.0.0.M6 isn't located in the repo http://repo.maven.apache.org/maven2. If you wan't to use this version you have to use the maven repo http://repo.spring.io/milestone. So add it to your POM file:

<repositories>
    <repository>
        <id>spring-milestone-repo</id>
        <url>http://repo.spring.io/milestone/</url>
    </repository>
</repositories>

I would recommend you to use the latest release version of spring-boot (1.5.8.RELEASE), not a milestone version. I don't know how your POM looks like, but you can define spring boot in your POM in different ways:

1. Using the Spring Boot parent POM

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
</parent>

Then you can add the dependencies you wish to use e.g.:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

See: https://spring.io/guides/gs/spring-boot/

2. Declare Spring-Boot in Dependency-Management

If you already using an own parent POM, you could also import the spring boot dependency management in your POM:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>1.5.8.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Same as in variant #1 you can declare afterwards the dependencies of spring boot you wish to use.


问:
convert array into proper JSON format for android using PHP
I am using Codeigniter to fetch rows. Please go through the below code.

```<code>//Model

public function selectData() {
    $query = $this->db->query('SELECT * FROM tbl_favourites WHERE favourites_status = 1');
    $count = $query->num_rows();

    if($count > 0)
        return $result = $query->result_array();
    else
        return 0;
}

//Controller

$all_favourites = $this->select->selectData();

if(!empty($all_favourites)) {
    foreach($all_favourites as $favourites)
        echo json_encode($favourites);
}
</code>```

From the above code, the output is

```<code>{"favourite_online_id":"3","favourite_online_url":"ddd","favourite_online_status":"0"}
{"favourite_online_id":"2","favourite_online_url":"http:\/\/www.google.com","favourite_online_status":"0"}
</code>```

But I want the output to be formatted properly to satisfy the android JSON.

The required output is,

```<code>[
  {
    "favourite_online_id": "3",
    "favourite_online_url": "ddd",
    "favourite_online_status": "0"
  },
  {
    "favourite_online_id": "2",
    "favourite_online_url": "http://www.google.com",
    "favourite_online_status": "0"
  }
]
</code>```

答:
instead of using

```<code>if(!empty($all_favourites)) {
    foreach($all_favourites as $favourites)
        echo json_encode($favourites);
}
</code>```

use directly

```<code>if(!empty($all_favourites)) {

        echo json_encode($all_favourites );
}
</code>```

Body:
I am using Codeigniter to fetch rows. Please go through the below code.

//Model

public function selectData() {
    $query = $this->db->query('SELECT * FROM tbl_favourites WHERE favourites_status = 1');
    $count = $query->num_rows();

    if($count > 0)
        return $result = $query->result_array();
    else
        return 0;
}

//Controller

$all_favourites = $this->select->selectData();

if(!empty($all_favourites)) {
    foreach($all_favourites as $favourites)
        echo json_encode($favourites);
}

From the above code, the output is

{"favourite_online_id":"3","favourite_online_url":"ddd","favourite_online_status":"0"}
{"favourite_online_id":"2","favourite_online_url":"http:\/\/www.google.com","favourite_online_status":"0"}

But I want the output to be formatted properly to satisfy the android JSON.

The required output is,

[
  {
    "favourite_online_id": "3",
    "favourite_online_url": "ddd",
    "favourite_online_status": "0"
  },
  {
    "favourite_online_id": "2",
    "favourite_online_url": "http://www.google.com",
    "favourite_online_status": "0"
  }
]

Body:
instead of using

if(!empty($all_favourites)) {
    foreach($all_favourites as $favourites)
        echo json_encode($favourites);
}

use directly

if(!empty($all_favourites)) {

        echo json_encode($all_favourites );
}